我是妄想,还是 JS 正则表达式支持可选的重复边界

Am I delusional, or does JS RegExp support optional repetition bounds?

本文关键字:边界 支持 正则表达式 妄想 还是 JS      更新时间:2023-09-26
/'d{,5}/.test('')

我以为这是一回事,但显然不是。一个人为什么会这么想?

量词{n1,n2}是一个有效的 JavaScript 正则表达式量词,它将匹配 n1 到 n2 次(包括 n1 到 n2 次(。

但是,{,n}并不表示量词,因为需要最小界限。有关语法生产和规则,请参见第 15.10.2.7 节量词。

以下都介绍了有效的范围量词:

/'d{3,5}/.test('12')      // false
/'d{3,5}/.test('1234')    // true
/'d{3,5}/.test('123456')  // false

另一方面,以下正则表达式不会创建量词。相反,作品被解析为没有特殊含义的文字文本:

/a{,5}b/.test('a{,5}b')   // true, at least in Chrome and IE

我以为这是一回事,但显然不是。一个人为什么会这么想?

如果你看得很快,它确实欺骗了你。但是算子的实现是不完整的,会失败。

可识别以下范围量词/运算符:

{n}     Match the preceding exactly n times
{n,}    Match the preceding at least n times
{n,m}   Match the preceding at least n but not more than m times
{n,}?   Match the preceding at least n times, but as few times as possible.
{n,m}?  Match the preceding between n and m times, but as few times as possible.

使用运算符时,您必须设置{n范围,,m}后面的所有内容都是可选的。

正确使用量词/运算符的示例。

"12345".match(/'d{3}/);    // => matches '123'
"12345".match(/'d{5,}/);   // => matches '12345', FAILS on 1234
"12345".match(/'d{1,4}/);  // => matches '1234'
"12345".match(/'d{2,}?/);  // => matches '12'
"12345".match(/'d{2,4}?/); // => matches '12'