如何修改此正则表达式以检测和忽略过多字符

How can this regular expression be modified to detect and ignore too many characters?

本文关键字:检测 字符 正则表达式 何修改 修改      更新时间:2023-09-26

我有以下字符串,我正在尝试使用正则表达式解析:

"id=12345,123456,1234567"

字符串是哈希值的一部分,可以通过以下方式之一显示:

"#id=12345" // single value
"#id=12345,123456,1234567" // multiple values
"#id=12345,123456,1234567&Another=Value" // one or more values followed by an ampersand.

只有包含 5 或 6 个字符的数字才有效,因此结果应如下所示:

['12345', '123456']

这是我目前拥有的正则表达式,但它还包括 7 位数字(上面的最后一个):

"id=12345,123456,1234567".match(/([0-9]{5,6})+/g); 

结果是:

["12345", "123456", "123456"] // Should only have two items

我该怎么做才能防止数字大于 6 位?

最简单的方法是使用单词边界:

/('b[0-9]{5,6}'b)+/g

而且我不确定您为什么在这里使用+量词...

/'b[0-9]{5,6}'b/g

这应该足够了。

顺便说一下,词界在'w'W'W'w'w$^'w之间匹配。