如何在正则表达式中使用“contains”(“Contains”或“%like%”)?
我有一个正则表达式来将 XML 节点与精确文本进行匹配:
<([\w]+)[^>]*>sample<\/\1>
它生成准确的节点名称,但我想像 C# 和 SQL 中那样应用正则表达式 (%LIKE%
)。
文字:
<Part>this is sample part</Part>
<Remarks>this is sample remark</Remarks>
<Notes>this is sample notes</Notes>
<Desc>sample</Desc>
预期的正则表达式结果应返回上述所有节点,但目前仅返回最后一个节点。
我创建了a sample here to test .
最佳答案
您可以使用XDocument
像这样解析 XML:
var s = @"<?xml version=""1.0""?>
<root>
<Part>this is sample part</Part>
<Remarks>this is sample remark</Remarks>
<Notes>this is sample notes</Notes>
<Desc>sample</Desc>
</root>";
var document = XDocument.Parse(s);
var names = document.Descendants()
.Elements()
.Where(x => x.Value.Contains("sample")) // all nodes with text having sample
.Select(a => a.Name.LocalName); // return the local names of the nodes
Console.WriteLine(string.Join("\n", names));
它打印:
使用 XPath 也可以实现同样的效果:
var names2 = document.Root.XPathSelectElements("//*[contains(text(), \"sample\")]");
var results = names2.Select(x => x.Name.LocalName));
要在 XML 无效的情况下回退到正则表达式,请使用
<(?:\w+:)?(\w+)[^<]*>[^<]*?sample[^<]*</(?:\w+:)?\1>
请参阅regex demo 。请注意(?:\w+:)?
匹配打开和关闭标记节点中的任意 namespace 。 [^<]
匹配除 <
之外的任何字符,所以不会溢出到下一个节点。
关于c# - 正则表达式 包含在 XML 元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44387603/