开发者

Why does this regular expression match?

开发者 https://www.devze.com 2023-02-16 16:17 出处:网络
I\'m trying to enlarge my r开发者_Python百科egexp knowledge but I have no clue why the following returns true:

I'm trying to enlarge my r开发者_Python百科egexp knowledge but I have no clue why the following returns true:

/[A-Z]{2}/.test("ABC")
// returns true

I explicity put {2} in the expression which should mean that only exactly two capital letters match.

According to http://www.regular-expressions.info/repeat.html:

Omitting both the comma and max tells the engine to repeat the token exactly min times.

What am I misunderstanding here?


You must anchor the regex using ^ and $ to indicate the start and end of the string.

/^[A-Z]{2}$/.test("ABC")
// returns false

Your current regex matches the "AB" part of the string.


It's matching AB, the first two letters of ABC.

To do an entire match, use the ^ and $ anchors:

/^[A-Z]{2}$/.test("ABC")

This matches an entire string of exactly 2 capital letters.


You should use ^[A-Z]{2}$ to match only the whole string rather than parts of it. In your sample, the regex matches AB - which are indeed two capital letters in a row.


you are missing ^ and $ characters in your regexp - beginning of the string and end of the string. Because they are missing your regular expression says "2 characters", but not "only two characters", so its matching either "AB" or "BC" in your string...


The doc don't lie :)

Omitting both the comma and max tells the engine to repeat the token exactly min times.

It says min times not max times

0

精彩评论

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

关注公众号