2016-05-23 145 views
0

注:我在改變建議的解決方案的情況下使用JavaScript。正則表達式:排除替換基於前綴的匹配

查找通過多個文件和更改屬性/參數之類的詞「計數」(例如countregister.countfunction(count)getCountincrementCount)我遇到了改變,如「打折」詞的問題,「各顯神通」 ,或「相遇」。

我意識到對於我的小用例*可以通過使用簡單的啓發式來避免此錯誤 - 查找以「count」爲前綴的已知字符分組並將它們排除在替換之外。

問題

有沒有辦法使用正則表達式來查找所有實例「計數」的 而忽視替換如果字符稱爲前綴分組被發現?

只是爲了澄清*

我知道我的「前綴啓發式」打破了,如果你想在一個大未知的搜索空間以概括爲除了「計數」換句話說,但它會足夠了現在。

+0

請訪問http:// javascript.info/tutorial/word-boundary –

+0

'.replace(/ \ bcount \ b/g,something)' – dandavis

+0

但是會有限制ies分解了像'''getCount'''這樣的情況? –

回答

0

您可以處理正則表達式是這樣的:

\b(get)?(count|Count)\b 

您應該應用不區分大小寫的開關。

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W) 
1st Capturing group (get)? 
    Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy] 
    Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data 
    get matches the characters get literally (case sensitive) 
2nd Capturing group (count|Count) 
    1st Alternative: count 
     count matches the characters count literally (case sensitive) 
    2nd Alternative: Count 
     Count matches the characters Count literally (case sensitive) 
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W) 
0

我不認爲有可能去排除路線,因爲在JavaScript中缺乏lookbehinds。

無論如何,對於您的「已知」前綴,難道不會容易嗎?允許?畢竟,你不能列出每一個在其中某處「計數」的正規單詞。允許您知道合法的前綴,並讓\b照顧其餘的:

  • 模式:(get|increment)count|\bcount\b //case insensitive

  • 取代:$1FOO

demo

+0

使用我的問題文本作爲演示非常聰明!哈哈 –

+0

你和@RudyTheHunter使用包含而不是專有集合的例子工作,但它會更困難。它使用的案件數量遠遠大於少數案件應該跳過的案件數量。 –