C# 正则表达式从大型html源中提取信息?

C# 正则表达式从大型html源中提取信息?,c#,C#,在众多的html源代码中,我有一些类似的元素 <option value=15>Bahrain - Manama</option> <option value=73>Bangladesh - Dhaka</option> <option value=46>Barbados - Bridgetown</option> <option value=285>Belarus - Minsk</option>

在众多的html源代码中,我有一些类似的元素

<option value=15>Bahrain - Manama</option>
<option value=73>Bangladesh - Dhaka</option>
<option value=46>Barbados - Bridgetown</option>
<option value=285>Belarus - Minsk</option>
<option value=48>Belgium - Brussels</option>
<option value=36>Belize - Belmopan</option>

这会删掉一些文本,但我或多或少会被困在想如何从文本中提取相关部分的问题上。我知道这很糟糕,但我正在学习:(

不要使用正则表达式-使用-现在您可以使用Linq检索选项元素并在一行中建立字典:

HtmlDocument doc = new HtmlDocument();
//remove "option" special handling otherwise inner text won't be parsed correctly
HtmlNode.ElementsFlags.Remove("option"); 
doc.Load("test.html");

var Places = doc.DocumentNode
                .Descendants("option")
                .ToDictionary(x => x.InnerText.Split('-')[1].Trim(),
                              x => x.Attributes["value"].Value);

为了从选项值中提取城市名称,上面使用
string.Split()
,在分隔的
-
上拆分,取第二个(城市)字符串并修剪任何前导或尾随空格。

不要使用正则表达式-使用-现在您可以使用Linq检索选项元素并在一行中建立字典:

HtmlDocument doc = new HtmlDocument();
//remove "option" special handling otherwise inner text won't be parsed correctly
HtmlNode.ElementsFlags.Remove("option"); 
doc.Load("test.html");

var Places = doc.DocumentNode
                .Descendants("option")
                .ToDictionary(x => x.InnerText.Split('-')[1].Trim(),
                              x => x.Attributes["value"].Value);

对于从选项值提取城市名称,上面使用
string.Split()
,在分隔
-
的基础上进行拆分,获取第二个(城市)字符串并修剪任何前导或尾随空格。

如果您要查找的唯一相关数据在
string[] options = Regex.Split(theSource, "<option value="); // Splits up the source which is downloaded from the url
要获取数字,如果需要获取更长的数字,可以使用指针循环if语句。如果数字不总是超过10,只需使用指针循环if语句并忽略第一行

然后我会重复使用字符串the string:

string[] place = Regex.Split(options[x], " - "); // split it immediately after the name
theString = place[0].substring(y, place[0].length - y); 
然后将它们添加到

Places.Add(theString, theInt);

如果代码不起作用,那么算法会起作用,只要确保拼写正确,并且如果您要查找的唯一相关数据在
string[] options = Regex.Split(theSource, "<option value="); // Splits up the source which is downloaded from the url
要获取数字,如果需要获取更长的数字,可以使用指针循环if语句。如果数字不总是超过10,只需使用指针循环if语句并忽略第一行

然后我会重复使用字符串the string:

string[] place = Regex.Split(options[x], " - "); // split it immediately after the name
theString = place[0].substring(y, place[0].length - y); 
然后将它们添加到

Places.Add(theString, theInt);

如果代码不能很好地工作,那么算法就会工作,只要确保拼写正确,并且变量正在做它们应该做的事情

你可以尝试使用它,这会让你更容易“巴林”是国家名称。你想忽略国家还是城市?@Ben Vogit是的!谢谢,我对打字感到困惑有点相关(但读起来总是很有趣)。是的,读起来很有趣。有很多值得思考的地方。谢谢。你可以试着使用它会让你“巴林”更容易一些是国家名称。你想忽略国家还是城市?@Ben Vogit是的!谢谢,我对打字感到困惑有点相关(但读起来总是很有趣)。是的,读起来很有趣。非常值得思考。谢谢。