我正在使用 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"}
<-- 每个逗号都不匹配。
最佳答案
正则表达式:
,\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
换句话说:匹配前面有零个或偶数个引号(直到字符串末尾)的任何逗号。
关于java - 用于匹配未被引号包围的逗号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2700953/