Regex,匹配标签内的文本,然后匹配同一字符串中不在该标签中的所有文本
本文关键字:文本 标签 然后 Regex 字符串 | 更新日期: 2023-09-27 18:11:35
我的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;