【问题标题】:A regex to match a comma that isn't surrounded by quotes一个匹配不被引号包围的逗号的正则表达式
【发布时间】:2011-02-11 15:47:48
【问题描述】:

我正在使用 Clojure,所以这是在 Java 正则表达式的上下文中。

这是一个示例字符串:

{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}

重要的位是每个字符串后面的逗号。我希望能够使用 Java 的 replaceAll 方法将它们替换为换行符。一个匹配 任何 逗号且未被引号包围的正则表达式即可。

如果我遇到的不好,请询问,我很乐意澄清任何事情。

编辑:抱歉标题中的混淆。我很久没醒了。

String: {:a "ab, cd efg",}

字符串:{:a 3, :b 3,}

String {:a "abcd,efg" :b "abcedg,e"}

【问题讨论】:

  • 你能添加一个每个逗号都匹配的例子,以及一个每个逗号都不匹配的例子

标签: java regex clojure


【解决方案1】:

正则表达式:

,\s*(?=([^"]*"[^"]*")*[^"]*$)

匹配:

{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}
                ^                  ^
                ^                  ^

和:

{:a "ab, cd efg",}
                ^
                ^

并且不匹配逗号:

{:a "abcd,efg" :b "abcedg,e"}

但是当转义引号会出现时,像这样:

{:a "ab,\" cd efg",} // only the last comma should match

那么正则表达式解决方案将不起作用。

正则表达式的简要说明:

,            # match the character ','
\s*          # match a whitespace character: [ \t\n\x0B\f\r] and repeat it zero or more times
(?=          # start positive look ahead
  (          #   start capture group 1
    [^"]*    #     match any character other than '"' and repeat it zero or more times
    "        #     match the character '"'
    [^"]*    #     match any character other than '"' and repeat it zero or more times
    "        #     match the character '"'
  )*         #   end capture group 1 and repeat it zero or more times
  [^"]*      #   match any character other than '"' and repeat it zero or more times
  $          #   match the end of the input
)            # end positive look ahead

换句话说:匹配前面有零个或偶数个引号的任何逗号(直到字符串的末尾)。

【讨论】:

  • 看起来你做的与我想要的相反。 :p 我想匹配字符串中/不是/的逗号。 :)
  • 啊,因为您没有转义字符串中的引号,所以我假设第一个和最后一个引号也是您文字的一部分。顺便说一句,我的正则表达式仍然正确。查看我的编辑。
  • 这对我的问题很有帮助,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多