簡體   English   中英

Truoble使用正則表達式從字符串獲取值

[英]Truoble getting value from string using 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也為空,即使它正確找到了我要查找的字符串。

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

XmlDocument另一種方法XmlDocument更干凈的方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM