Having a html string that looks like this:
有一个看起来像这样的html字符串:
<div class="mainClass" id="mainId" title="This is the title" customtag="+500"></div>
I want to get 500
我想要500
What I have done so far:
到目前为止我做了什么:
string k = @"<div class=""mainClass"" id=""mainId"" title=""This is the title"" customtag=""+500""></div>";
//or
string k = "<div class=\"mainClass\" id=\"mainId\" title=\"This is the title\" customtag=\"+500\"></div>";
// Using this regex (?<=customtag="\+)\d+(?=">)
Regex regex = new Regex(@"(?<=customtag=""\+)\d+(?="">)");
Match match = regex.Match(k);
Console.WriteLine(match.Value);
After running it, match.Value is empty even if when testing the regex in a text editor it correctly finds the string I'm looking for.
运行之后,即使在文本编辑器中测试正则表达式时,match.Value也是空的,它正确地找到了我正在寻找的字符串。
2 个解决方案
#1
0
string s = "<div class=\"mainClass\" id=\"mainId\" title=\"This is the title\" customtag=\"+500\"></div>";
Regex regex = new Regex("customtag=\"\\+(\\d+)\"");
if (regex.Match(s).Groups.Count >= 1)
{
Console.WriteLine(regex.Match(s).Groups[1].Value);
}
#2
0
Another approach with XmlDocument
- IMO the cleaner way:
使用XmlDocument的另一种方法 - IMO更清洁的方式:
string k = "<div class=\"mainClass\" id=\"mainId\" title=\"This is the title\" customtag=\"+500\"></div>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(k);
string result = doc.DocumentElement.Attributes["customtag"].Value;
Fiddle: https://dotnetfiddle.net/pAHXMp
#1
0
string s = "<div class=\"mainClass\" id=\"mainId\" title=\"This is the title\" customtag=\"+500\"></div>";
Regex regex = new Regex("customtag=\"\\+(\\d+)\"");
if (regex.Match(s).Groups.Count >= 1)
{
Console.WriteLine(regex.Match(s).Groups[1].Value);
}
#2
0
Another approach with XmlDocument
- IMO the cleaner way:
使用XmlDocument的另一种方法 - IMO更清洁的方式:
string k = "<div class=\"mainClass\" id=\"mainId\" title=\"This is the title\" customtag=\"+500\"></div>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(k);
string result = doc.DocumentElement.Attributes["customtag"].Value;
Fiddle: https://dotnetfiddle.net/pAHXMp