开发者

Difference between two regex pattern in javascript

I my application I am using below regex for pattern matching.

Original Pattern :

/(\w+\.){2,}/ig

Above pattern added in one array. Since this pattern has comma ( , ) after 2, creating problem in some environment.

As we know below concept in regex :

 {n} - matches n times
 {n, m} - matches at least n times, but not more than m times

So I have removed comma present after 2, because in above pattern no value exist after comma.

Pattern after removing comma :

/(\w+\.){2}/ig

As per above change i have resolved environment problem which i was facing earlier.

So here, I just wanted to know that by removing comma after 2 cr开发者_高级运维eates any problem while matching, for above given case.


{2} means match if it appears exactly 2 times, and {2,} means 2 times or above. Depending on the usage, this may or may not matter.

For example, if you want to validate whether the string contains 2 or more \w+\., then the comma doesn't matter. However, if you want to replace those 2 or more \w+\. with something else, the comma will affect the result.

'foo.bar.baz.'.replace(/(\w+\.){2}/ig, '~') == '~baz.'
'foo.bar.baz.'.replace(/(\w+\.){2,}/ig, '~') == '~'


{2,} means two or more. There is no max limit. With this, {0,} is the same as *, and {1,} is the same as +

To summarize:

{n} match n times
{n,m} match at least n times, but not more than m times
{n,} match at least n times

Refer this for details

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜