如何在正则表达式中使用“包含”(“包含”或“%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));


它打印:

c# - 正则表达式包含在XML元素中-LMLPHP

使用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+:)?匹配打开和关闭标记节点中的任意名称空间。 [^<]匹配除<以外的任何字符,因此不会溢出到下一个节点。

10-06 10:58
查看更多