2016-02-16 165 views
5

我試圖在任何一個字詞('eed' or 'eedly')出現之前,從存在元音的字詞中替換'eed' and 'eedly' with 'ee'正則表達式從字符串中刪除字符串

因此,例如,單詞indeed將變成indee,因爲在'eed'之前發生了元音('i')。另一方面,詞'feed'不會改變,因爲在後綴'eed'之前沒有元音。

我有這個正則表達式:(?i)([aeiou]([aeiou])*[e{2}][d]|[dly]\\b) 你可以看到這個here發生了什麼。

正如您所看到的,這可以正確識別以'eed'結尾的單詞,但它不能正確識別'eedly'

而且,當它的替代,它正在取代與'eed'結尾的所有單詞,甚至話像feed它不應該刪除eed

我應該在這裏考慮,以使其正確識別基於我指定的規則的話?

回答

5

您可以使用:eedeedly確保沒有在同一個詞至少一個元音在此之前

str = str.replaceAll("(?i)\\b(\\w*?[aeiou]\\w*)eed(?:ly)?", "$1ee"); 

Updated RegEx Demo

\\b(\\w*?[aeiou]\\w*)之前。

加快這個表達式可以使用否定表達的正則表達式:

\\b([^\\Waeiou]*[aeiou]\\w*)eed(?:ly)? 

正則表達式破碎:

\\b     # word boundary 
(     # start captured group #` 
    [^\\Waeiou]*  # match 0 or more of non-vowel and non-word characters 
    [aeiou]   # match one vowel 
    \\w*    # followed by 0 or more word characters 
)     # end captured group #` 
eed     # followed by literal "eed" 
(?:     # start non-capturing group 
    ly    # match literal "ly" 
)?     # end non-capturing group, ? makes it optional 

更換是:

"$1ee" which means back reference to captured group #1 followed by "ee" 
+1

這工作完美。謝謝。你介意再解釋一下這個邏輯嗎?我對正則表達式相對比較陌生,所以我想真正瞭解爲什麼這會起作用。 @anubhava – Anderology

+0

確定檢查更新的答案與解釋。 – anubhava

+1

非常感謝你! – Anderology

1

˚F之前找到DLY d。否則您的正則表達式評估在找到eed後停止。

(?i)([aeiou]([aeiou])*[e{2}](dly|d)) 
相關問題