Reputation: 154858
I'm trying to enlarge my regexp 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?
Upvotes: 1
Views: 218
Reputation: 29927
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
Upvotes: 1
Reputation: 8685
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...
Upvotes: 1
Reputation: 46617
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.
Upvotes: 1
Reputation: 723729
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.
Upvotes: 1
Reputation: 14154
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.
Upvotes: 6