[英]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.