4

考虑以下字符串

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

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

[^\\]"

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

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

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

"(?<!\\)
4

3 回答 3

3
"(?<!\\")

是你要找的

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

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

会做

解释:

  • (?<!\\")- 负面回顾。指定在主表达式之前无法匹配的组
  • (?!\\")- 负前瞻。指定在主表达式之后无法匹配的组
  • "[a-zA-Z0-9]*"- 在常规引号之间匹配的字符串

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

于 2012-06-18T11:27:51.853 回答
1

你几乎明白了,将引号移到后面,例如:

(?<!\\)"

还要注意像这样的情况

"escaped" backslash \\"string\"

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

(?<!\\)(?:\\\\)*"
于 2012-06-18T12:13:40.497 回答
0

试试这个

(?<!\\)(?<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
}
于 2012-06-18T11:26:51.360 回答