2013-10-08 163 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