Thaddee Tyl
Thaddee Tyl

Reputation: 1214

Regular Expression form {m,n} does not use upper limit

My understanding was that the regexp form a{m,n} would match a at most n times. However, the following snippet does not work as I would expect (this is javascript):

/\{{2,2}/.exec ('df{{{df')
// [ '{{', index: 2, input: 'df{{{df' ]

Shouldn't it return null?

Upvotes: 1

Views: 284

Answers (4)

agent-j
agent-j

Reputation: 27943

It is matching the text because there are two. That satisfies the requirements your regex specifies. If you want to prevent extras from matching use a negative lookahead: (?!\{).

(?:^|[^{])(\{{2,2}(?!\{))

Then, use the first captured group.

Edit, by the way, the the ,2 in {2,2} is optional in this case, since it's the same number.

Edit: Added usage example to get rid of first matched character. (Javascript doesn't support negative lookbehind.

var myRegexp = /(?:^|[^{])(\{{2,2}(?!\{))/g;
var match = myRegexp.exec(myString);
alert(match[1]);

Upvotes: 5

Lucent Fox
Lucent Fox

Reputation: 1795

What your expression states is find {{ anywhere in the string, which it will find. If you want to find only {{ and not {{{ then you need to specify that you want to find:

/[^{]\{{2,2}[^{]/

In English:

[Any Character Not a {] followed by [Exactly 2 {] followed by [Any Character Not a {]

This will match a{{b but not a{b and not a{{{{b

Upvotes: 3

maerics
maerics

Reputation: 156562

That regular expression is looking for exactly two left-curly-braces ({{), which it finds in the string "df{{{df" at index 2 (immediately after the first "df"). Looks right to me.

Upvotes: 1

antlersoft
antlersoft

Reputation: 14751

It matches because it contains a substring with exactly 2 left braces. If you want it to fail to match, you have to specify that anything outside the 2 left braces you are looking for can't be a left brace.

Upvotes: 1

Related Questions