2013-10-08 82 views
0

我想創建一個正則表達式,匹配一定長度的字符中的一組字符。 AKA與升的5或更大 匹配字符的hello goodbye low loving正則表達式匹配一定長度的字符

字長度的列表

[它將匹配l l l(在hello兩個和一個在loving)]。

我需要這個替換用例。

因此代替字母爲£將輸出

he££o goodbye low £oving

我指的是這個問題,regular-expression-match-a-word-of-certain-length-which-starts-with-certain-let,但我不能工作,如何匹配的符號從整個字更改爲一個字符這個單詞。

我有,但我需要將字長檢查添加到匹配的正則表達式。

myText = myText.replace(/l/g, "£"); 
+0

請說明,寫更多:應該做什麼替代? 'hero再見低Roving'? –

+0

提供輸入和預期輸出。發佈不符合預期的代碼。 – Aashray

+0

看看這個[fiddle](http://jsfiddle.net/hari_shanx/ynKdh/)。這是你想要的嗎? – Harry

回答

4

您可以使用這樣一個匿名函數:

var str = 'hello goodbye low loving'; 
var res = str.replace(/\b(?=\S*l)\S{5,}/g, function(m) { 
    return m.replace(/l/g, "£"); 
}); 
alert(res); 

jsfiddle

我用超前只是讓匿名函數不會爲每個單個5(或更多)字母單詞調用。

編輯:一個正則表達式快一點是:\b(?=[^\sl]*l)\S{5,}

如果JS曾經支持佔有慾量詞,這樣會更快:\b(?=[^\sl]*+l)\S{5,}


正則表達式

\b   // matches a word boundary; prevents checks in the middle of words 
(?=  // opening of positive lookahead 
    [^\sl]* // matches all characters except `l` or spaces/newlines/tabs/etc 
    l  // matches a single l; if matched, word contains at least 1 `l` 
)   // closing of positive lookahead 
\S{5,}  // retrieves word on which to run the replace 
+0

+1我喜歡這樣向前看。有人下了票? – Harry

+0

任何使用?非常性感,但可能會讓整個事情在大詞彙和大文本上有點呆滯?我想我將不得不將它添加到測試中。 – tigerswithguitars

+0

@tigerswithguitars你可以用'[^ ​​\ sl] *'而不是'\ S *'加速它。如果JS支持所有格量​​詞,那麼它會加快它的速度:) – Jerry

0

這應該工作:

var s='hello goodbye low loving'; 
r = s.replace(/\S{5,}/g, function(r) { return r.replace(/l/g, '£'); }); 
// he££o goodbye low £oving 
+1

用匿名函數進行嵌套替換!非常整潔,我不知道你可以做到這一點。看起來不錯。 – tigerswithguitars