简体   繁体   English

正则表达式格式{m,n}不使用上限

[英]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. 我的理解是正则表达式形式a{m,n}最多匹配a次。 However, the following snippet does not work as I would expect (this is javascript): 但是,以下代码段无法正常运行(这是javascript):

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

Shouldn't it return null? 它不应该返回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. 顺便说一下,在这种情况下, {2,2} ,2是可选的,因为它是相同的数字。

Edit: Added usage example to get rid of first matched character. 编辑:添加了用法示例以摆脱第一个匹配的字符。 (Javascript doesn't support negative lookbehind. (JavaScript不支持负向后看。

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 { ] [不是{任何字符,然后是[正好2 { ],然后是[不是{任何字符,

This will match a{{b but not a{b and not a{{{{b 这将匹配a{{b但不是a{b而不是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. 如果您希望它不匹配,则必须指定要查找的2个左括号以外的任何内容都不能为左括号。

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"). 该正则表达式恰好寻找两个左大括号( {{ ),它在索引2的字符串“ df{{{df ”中找到(紧接在第一个“ df”之后)。 Looks right to me. 在我看来不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM