2015-04-30 41 views
2

我是新來的正則表達式,但我認爲我的問題應該解決使用它。基本上,我想用「狗」替換字符串中的空格,只要「貓」或「鳥」或「狗」不在之前或之後。Java正則表達式 - 空格和匹配詞

實施例:

Good Dog = Good Dog 
    Large Brown = Large Dog Brown 
    Cat Ugly = Cat Ugly 

因此,只有第二串將被修改。我可以像這樣輕鬆地處理字符串替換等,但我很想知道這是否應該在正則表達式中完成。

回答

4

您正在尋找lookaround機制。您的代碼可以看看或多或少像

yourString = yourString.replaceAll("(?<!cat|bird|dog)\\s(?!cat|bird|dog)"," dog ") 
//         ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ 
//        negative look-behind negative look-ahead 

您可以通過使用情況旗(?i)提高不敏感的regex。
您還可以添加word boundaries\b)以確保您匹配的是整個單詞,而不僅僅是其部分,如cataclysm

演示(我還用non-capturing group (?:...)來提高性能略):

String[] data ={ "Good Dog", "Large Brown", "Cat Ugly"}; 
for (String s : data){ 
    System.out.println(s.replaceAll("(?i)(?<!\\b(?:cat|bird|dog)\\b)\\s(?!\\b(?:cat|bird|dog)\\b)"," dog ")); 
} 

輸出:

Good Dog 
Large dog Brown 
Cat Ugly 
+0

@RealSkeptic我在改善這個答案:)中間一直在尋找正確的鏈接這可以爲讀者提供更多信息。 – Pshemo

+1

非常感謝你這麼多! – user2816352

+1

@ user2816352不客氣:) – Pshemo