2010-04-23 192 views
5

我使用的是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"} < - 每一個逗號都不匹配。

+0

你可以添加一個例子,其中每個逗號匹配,並且每個逗號不匹配的一個例子 – mkoryak 2010-04-23 18:22:45

回答

18

正則表達式:

,\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 

換句話說,匹配具有零任何逗號,或者偶數報價在它前面的(直到字符串的結尾)。

+0

看起來你做了與我想要的相反的東西。 :p 我想匹配/不在字符串中的逗號。 :) – Rayne 2010-04-23 18:30:20

+0

啊,既然你沒有逃過你的字符串中的引號,我認爲第一個和最後一個引號也是你文字的一部分。順便說一句,我的正則表達式仍然是正確的。看我的編輯。 – 2010-04-23 18:37:59

相關問題