【问题标题】:Regex - select but not [duplicate]正则表达式 - 选择但不是 [重复]
【发布时间】:2017-03-25 06:34:42
【问题描述】:

我是正则表达式的新手,想为我的 .net 应用程序创建两个正则表达式。

我有一个存储 xml 的输入变量。下面是xml

<Row>
......
</Row>
<Row {optional}>
.... 
</Row>
<Row {optional} header="true" {optional}>
</Row>

我想要 2 个正则表达式: 1. 选择 header="true" 的行的正则表达式 2. 选择没有 header="true" 的行的正则表达式

正则表达式只需要考虑开始标签。例如:

【问题讨论】:

    标签: .net regex c#-4.0


    【解决方案1】:

    Regex 不是在 .NET 中处理 xml 的最佳选择 如果您使用的是 .NET 3.5 或更高版本,请查看 LINQ to xml 对于旧版本的运行时,请参阅XmlDocument and XPath

    使用 LINQ,您的代码将是这样的:

        var document = XDocument.Load("path to your file"); // or XDocument.Parse if you have content in a string
        var elementsWithHeaders = document.Descendants("Row").Where(x => 
             x.Attribute("header")!=null && x.Attribute("header").Value == "true");
    

    这段代码不是最优的,但是为了提高效率,我需要了解更多关于你的 xml 结构的假设

    如果你使用 C#6,你也可以使用 null-conditional operator 来简化上面的谓词

        var elementsWithHeaders = document.Descendants("Row").Where(x => 
             x.Attribute("header")?.Value == "true");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多