首页 > 解决方案 > 如何在单个 foreach 中匹配两个字符串?

问题描述

我正在使用正则表达式来匹配文件中的字符,但我想匹配该文件中的 2 个不同的字符串,但它们不止一次出现,这就是我使用循环的原因。我可以匹配单个字符串,但不能匹配 2 个字符串。

Regex celcius = new Regex(@"""temp"":\d*\.?\d{1,3}"); 
foreach (Match match in celcius.Matches(htmlcode))
{ 
    Regex date = new Regex(@"\d{4}-\d{2}-\d{2}");
    foreach (Match match1 in date.Matches(htmlcode))
    {
        string date1 = Convert.ToString(match1.Value);
        string temperature = Convert.ToString(match.Value);
        Console.Write(temperature + "\t" + date1);
    }
}

html代码:

{"temp":287.05,"temp_min":286.932,"temp_max":287.05,"pressure":1019.04,"sea_level":1019.04,"grnd_level":1001.11,"humidity":89,"temp_kf":0.12},"weather":[{"id":804,"main":"Clouds","description":"overcast
clouds","icon":"04n"}],"clouds":{"all":100},"wind":{"speed":0.71,"deg":205.913},"sys":{"pod":"n"},"dt_txt":"2019-09-22
21:00:00"},{"dt":1569196800,"main":{"temp":286.22,"temp_min":286.14,"temp_max":286.22,"pressure":1019.27,"sea_level":1019.27,"grnd_level":1001.49,"humidity":90,"temp_kf":0.08},"weather":[{"id":804,"main":"Clouds","description":"overcast
clouds","icon":"04n"}],"clouds":{"all":99},"wind":{"speed":0.19,"deg":31.065},"sys":{"pod":"n"},"dt_txt":"2019-09-23
00:00:00"},{"dt":1569207600,"main":{"temp":286.04,"temp_min":286,"temp_max":286.04,"pressure":1019.38,"sea_level":1019.38,"grnd_level":1001.03,"humidity":89,"temp_kf":0.04},"weather":

标签: c#regexforeach

解决方案


我不认为你有 HTML。我认为您有一个称为 JSON(JavaScript 对象通知)的集合,它是一种有效传递数据的方法。

所以,这是您的“HTML”对象之一。

{
    "temp":287.05,
    "temp_min":286.932,
    "temp_max":287.05,
    "pressure":1019.04,
    "sea_level":1019.04,
    "grnd_level":1001.11,
    "humidity":89,
    "temp_kf":0.12},
    "weather":[{
        "id":804,
        "main":"Clouds",
        "description":"overcast clouds",
        "icon":"04n"
    }],
    "clouds":{
        "all":100
    },
    "wind":{
        "speed":0.71,"deg":205.913
    },
    "sys":{
        "pod":"n"
    },
    "dt_txt":"2019-09-22 21:00:00"
}

因此,我建议使用 C# Web 帮助程序转换该行并直接解析对象。

//include this library
using System.Web.Helpers;

//parse your htmlcode using this loop
foreach(var line in htmlcode)
{
    dynamic data = JSON.decode(line);
    string temperature = (string)data["temp"];
    string date = Convert.ToDateTime(data["dt_txt"]).ToString("yyyy-MM-dd");
    Console.WriteLine($"temperature: {temperature} date: {date}"");
}

推荐阅读