我试图在彼此之后找到正好三个点,而不是4个而不是仅仅3个。
e.g:
首先是:
return text.replace(/\.{3}/g, 'FOUND!');
但是效果不好。有什么想法吗?
答案 0 :(得分:4)
你想要的正则表达式:
/(^|[^.])\.{3}([^.]|$)/g
你想要的JS替换:
text.replace(/(^|[^.])\.{3}([^.]|$)/g, '$1FOUND!$2');
以下是正则表达式的细分:
(^|[^.])
:没有字符^
或|
字符不是点[^.]
\.{3}
:后跟三个点([^.]|$)
后跟一个不是点[^.]
或|
字符串结尾的字符$
$1
:包含第一个捕获组$2
:包含最后一个捕获组此方法的唯一缺点是,将跳过由单个字符分隔的...
的任何组合,因此您必须运行替换两次:
... ... ... ... ... ... => FOUND!!! ... FOUND!!! ... FOUND!!! FOUND!!!
测试字符串:
"This should be found -> ... \
This should not be found -> .... \
Something will be found here -> .. .. ...... ... .. \
Multiple found -> ... ... .. ... ... .. \
... <- That's found \
Next line will be found \
..."
输出1次迭代:
"This should be found -> FOUND!
This should not be found -> ....
Something will be found here -> .. .. ...... FOUND! ..
Multiple found -> FOUND! ... .. FOUND! ... ..
FOUND! <- That's found
Next line will be found
FOUND!"
输出2次迭代:
"This should be found -> FOUND!
This should not be found -> ....
Something will be found here -> .. .. ...... FOUND! ..
Multiple found -> FOUND! FOUND! .. FOUND! FOUND! ..
FOUND! <- That's found
Next line will be found
FOUND!"
答案 1 :(得分:1)
你可以试试这个:
return text.replace(/(^|[^.])\.{3}(?!\.)/, '$1FOUND!');
这样的工作原理如下:
negative lookahead
由于我们在第一个字符上使用贪婪匹配,因此我们必须将其添加到替换字符,因此$1
。
如果需要替换这3个点的每个实例,请在正则表达式的末尾添加标记g
。看起来像这样:
/(^|[^.])\.{3}(?!\.)/g
标志g
表示它将执行全局匹配,而不是匹配一次。
答案 2 :(得分:0)