正则表达式匹配不包含引号的逗号
我使用的是Clojure,所以这是在Java正则表达式的上下文中。正则表达式匹配不包含引号的逗号
下面是一个例子的字符串:
{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}
重要比特的每个字符串之后的逗号。我希望能够用Java的replaceAll方法用换行符替换它们。一个匹配任何逗号的正则表达式不会被引号包围。
如果我遇到不好,请问,我会很乐意澄清任何事情。
编辑:抱歉标题混乱。我没有清醒很久。
字符串:{:a "ab, cd efg",}
< - 在本例中,最后的逗号会匹配,但引号内的逗号不会匹配。
字符串:{:a 3, :b 3,}
< - 每个逗号都匹配。
字符串{: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
换句话说,匹配具有零任何逗号,或者偶数报价在它前面的(直到字符串的结尾)。
看起来你做了与我想要的相反的东西。 :p 我想匹配/不在字符串中的逗号。 :) – Rayne 2010-04-23 18:30:20
啊,既然你没有逃过你的字符串中的引号,我认为第一个和最后一个引号也是你文字的一部分。顺便说一句,我的正则表达式仍然是正确的。看我的编辑。 – 2010-04-23 18:37:59
你可以添加一个例子,其中每个逗号匹配,并且每个逗号不匹配的一个例子 – mkoryak 2010-04-23 18:22:45