使用JavaScript RegExp检测省略号的问题

时间:2018-02-14 18:06:30

标签: javascript regex regex-lookarounds

我有一些字符串意味着包含三个点......但有时它们只包含一行中的两个点,或者连续多于三个点。我正在尝试检测点太多或太少的字符串。

此正则表达式有效,但仅适用于Chrome: /((?<![.])[.]{2}(?![.])|(?<![.])[.]{4,}(?![.]))/g

其他浏览器的JavaScript RegExp引擎不支持lookbehinds,从我读过的内容来看,我无法重写这一点以使lookbehind成为一种先行,因为正则表达式已经有了前瞻。

也许我根本不需要基于RegExp的解决方案?但是,我没有看到它。

字符串匹配模式:

I have too many dots....and that's a problem
................
...Hey, that's not going to work..

字符串不匹配模式:

Here's a big success ...and that's great!
0.30.

1 个答案:

答案 0 :(得分:1)

我认为你过分思考这一点。只需定位2个点或更多点的所有位置,忘记不匹配...,因为无论如何都是您的替代品。

See regex in use here

\.{2,}

替换:...

&#13;
&#13;
var s = `I have too many dots....and that's a problem
................
...Hey, that's not going to work..

Here's a big success ...and that's great!
0.30.`
var r = /\.{2,}/g

console.log(s.replace(r, '...'))
&#13;
&#13;
&#13;