使用正则表达式从字符串中获取值

时间:2017-04-28 05:26:52

标签: c# regex

有一个看起来像这样的html字符串:

<div class="mainClass" id="mainId" title="This is the title" customtag="+500"></div>

我想 500

到目前为止我做了什么:

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);

运行之后,即使在文本编辑器中测试正则表达式时,match.Value也是空的,它正确地找到了我正在寻找的字符串。

2 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分:0)

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;

小提琴:https://dotnetfiddle.net/pAHXMp