用于匹配未被引号括起的逗号的正则表达式
我正在使用Clojure,所以这是在Java正则表达式的上下文中。
这是一个示例字符串:
{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}
重要的位是每个字符串后面的逗号。 我希望能够用Java的replaceAll方法用换行符替换它们。 正则表达式将匹配任何未被引号括起的逗号。
如果我没遇好,请问,我会高兴地澄清一切。
编辑:对不起标题中的混淆。 我没有醒来很久。
字符串: {:a "ab, cd efg",}
< – 在此示例中,末尾的逗号将匹配,但引号内的逗号不匹配。
字符串: {:a 3, :b 3,}
< – 每个逗号匹配。
String {:a "abcd,efg" :b "abcedg,e"}
< – 每个逗号都不匹配。
正则表达式:
,\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
换句话说:匹配任何前面有零或者偶数引号的逗号(直到字符串结尾)。