c# - 如何在单个 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":
解决方案
我不认为你有 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}"");
}
推荐阅读
- oracle11g - 从 CLOB 列中提取某些行
- php - PHP - 将相同长度的数组合并为关联
- sqlite - 如何在 Raspberry 上的 SQLite 中创建表
- datediff - 如何计算 apache Drill sql 中的日期差异以在几分钟内获得输出?
- recursion - 在递归函数中使用局部变量
- bash - 如何使用shell脚本运行exe
- python - 如何根据osmnx上的一些“手动选择”节点绘制路径?
- spotify - 希望从经过身份验证的 Spotify 用户帐户中获取 Artist_id
- typescript - 如何使用 Protractor 从 TypeScript 中的函数返回数组?
- c++ - C++中结构数组的clang格式奇怪的缩进