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?
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]);
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.