【问题标题】:.NET Regex: negate previous character for the first character in string.NET Regex:否定字符串中第一个字符的前一个字符
【发布时间】:2012-06-18 11:22:28
【问题描述】:

考虑以下字符串

"Some" string with "quotes" and \"pre-slashed\" quotes

使用正则表达式,我想找到所有前面没有斜线的双引号。所以我希望正则表达式为例句找到四个匹配项 这……

[^\\]"

...只会找到其中三个。我想这是因为正则表达式的状态机首先验证命令以否定斜杠的存在。

这意味着我需要编写一个带有某种look-behind 的正则表达式,但我不知道如何使用这些lookaheads 和lookbehinds...我什至不确定这就是我正在寻找的。

以下尝试返回 6,而不是 4 匹配...

"(?<!\\)

【问题讨论】:

    标签: c# .net regex


    【解决方案1】:
    "(?<!\\")
    

    是你要找的东西

    如果你想匹配“Some”和“quotes”,那么

    (?<!\\")(?!\\")"[a-zA-Z0-9]*"
    

    会的

    解释:

    • (?&lt;!\\") - 消极的后视。指定在主表达式之前无法匹配的组
    • (?!\\") - 负前瞻。指定主表达式后无法匹配的组
    • "[a-zA-Z0-9]*" - 匹配正则引号的字符串

    这意味着 - 匹配之前没有 \" 和之后没有 \" 的任何内容,但是包含在双引号内

    【讨论】:

      【解决方案2】:

      你几乎明白了,把引号移到后面,比如:

      (?<!\\)"
      

      还要注意像

      这样的情况
      "escaped" backslash \\"string\"
      

      您可以使用这样的表达式来处理这些:

      (?<!\\)(?:\\\\)*"
      

      【讨论】:

        【解决方案3】:

        试试这个

        (?<!\\)(?<qs>"[^"]+")
        

        说明

        <!--
        (?<!\\)(?<qs>"[^"]+")
        
        Options: case insensitive
        
        Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!\\)»
           Match the character “\” literally «\\»
        Match the regular expression below and capture its match into backreference with name “qs” «(?<qs>"[^"]+")»
           Match the character “"” literally «"»
           Match any character that is NOT a “"” «[^"]+»
              Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
           Match the character “"” literally «"»
        -->
        

        代码

        try {
            if (Regex.IsMatch(subjectString, @"(?<!\\)(?<qs>""[^""]+"")", RegexOptions.IgnoreCase)) {
                // Successful match
            } else {
                // Match attempt failed
            } 
        } catch (ArgumentException ex) {
            // Syntax error in the regular expression
        }
        

        【讨论】:

          猜你喜欢
          • 2021-04-27
          • 2013-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-29
          • 2023-02-23
          • 1970-01-01
          相关资源
          最近更新 更多