正则表达式匹配一定长度的单词中的字符

时间:2013-10-08 08:47:35

标签: javascript regex str-replace

我正在尝试创建一个与一定长度的单词中的一组字符匹配的正则表达式。

包含hello goodbye low loving

列表的AKA

单词长度为5或更大 匹配字符l [它将匹配l l lhello中的两个和loving中的一个)]。

我需要这个用于替换用例。

因此将字母替换为£将输出

he££o goodbye low £oving

我指的是这个问题regular-expression-match-a-word-of-certain-length-which-starts-with-certain-let,但我无法弄清楚如何将整个单词中的匹配符号更改为单词中的字符。

我有,但我需要将字长检查添加到匹配的正则表达式。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
相关问题