[英]Regex, match text inside a tag, then match all text not in that tag both from same string?
我對Regex感到很吃驚,但感到驚訝的是,我能夠達到我自己所做的一切。
到目前為止,我已經知道了:
string text = "Whoa here is some very cool text.<phone>222-222-5555</phone><timesCalled>6</timescalled>";
Regex phoneRegex = new Regex(@"<phone>(.*?)<\/phone>");
Regex calledRegex = new Regex(@"<timesCalled>(.*?)<\/timesCalled>");
string phone = phoneRegex.Match(text).Value;
string timesCalled = calledRegex.Match(text).Value;
這些都給了我完整的標簽和里面的值,我該怎么做,使其只返回標簽內的內容? 我還需要一個最終的正則表達式,該表達式將返回不在這些標記內的所有文本,所以Whoa here is some very cool text.
從上面的例子。 如果重要的話,特殊標簽將始終出現在普通文本之后。
編輯:感謝所有的答案,盡管如此,我仍然需要最終的正則表達式。
到目前為止,我已經嘗試過了:
string pattern = @"^" + phoneRegex.Match(text).Value + calledRegex.Match(text).Value;
Regex textRegex = new Regex(pattern);
string normalText = textRegex.Match(text).Groups[1].Value;
但是那什么也沒返回。
您要獲取組的值:
calledregex.Match(text).Groups[1].Value
組基於1。
如何使用Xml類讀取/解析XML?
var doc = XElement.Parse("<root>" + text + "</root>");
string phone = doc.Descendants("phone").First().Value;
這是我的建議,可讓您有機會使用更多帶有值的標簽。
string text = "Whoa here is some very cool text.<phone>222-222-5555</phone><timesCalled>6</timesCalled>";
Regex regex = new Regex(@"<(?<tag>[^>]*)>(?<value>[^<]*)</\k<tag>>");
Match match = regex.Match(text);
string phone = match.Groups["value"].Captures[match.Groups["tag"].Captures.OfType<Capture>().FirstOrDefault(item => item.Value == "phone").Index].Value;
string timesCalled = match.Groups["value"].Captures[match.Groups["tag"].Captures.OfType<Capture>().FirstOrDefault(item => item.Value == "timesCalled").Index].Value;
匹配的Value
是所有與模式匹配的值。 如果只需要分組的內容(標簽中的內容),則必須通過Groups
屬性訪問它們。
string phone = phoneRegex.Match(text).Groups[1].Value;
string timesCalled = calledregex.Match(text).Groups[1].Value;
在內聯xml / html的情況下,我也將忽略大小寫,有時標簽大小寫可能會很奇怪。
string text = "Whoa here is some very cool text.<phone>222-222-5555</phone><timesCalled>6</timesCalled>";
Regex phoneRegex = new Regex(@"<phone>(.*?)<\/phone>", RegexOptions.IgnoreCase);
Regex calledRegex = new Regex(@"<timesCalled>(.*?)<\/timesCalled>", RegexOptions.IgnoreCase);
string phone = phoneRegex.Match(text).Groups[1].Value;
string timesCalled = calledRegex.Match(text).Groups[1].Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.