简体   繁体   English

概念-为什么match()看似去掉括号?

[英]Concept - Why does match() seemingly strip parentheses?

I did 我做了

temp = '(test)';
temp.match(temp);

and got back 然后回来

0:'test'
1:'test'

Where did the parentheses go? 括号在哪里?

Update: 更新:

Tested in regexpal.com and found similar. 在regexpal.com中测试,发现类似。

However, switching to {} did not have same concern. 但是,切换到{}并没有同样的问题。

Clarification 澄清度

temp is "intended" to be a string. temp是“预期”为字符串。 Not sure why it would be considered something else. 不知道为什么会考虑其他东西。

Parentheses are metacharacters (specifically capturing parentheses ) in regular expressions (note that if you pass a string to the match method it will be implicitly converted to a regular expression). 括号是正则表达式中的元字符(特别是捕获括号 )(请注意,如果将字符串传递给match方法,它将被隐式转换为正则表达式)。 You have to escape them if you want them to be taken literally (since you are dealing with a string, you also have to escape the escape character so that it will still exist when converted to a regex … and by then the regex won't match the original string). 如果要按字面意义使用它们,则必须对它们进行转义(由于您正在处理字符串,因此还必须对转义符进行转义,以便在转换为regex时它仍然存在……到那时,regex不会匹配原始字符串)。

The argument to .match() is treated as a regular expression. .match()的参数被视为正则表达式。 Parentheses are meta-characters that mean something in that context. 括号是在该上下文中表示某些含义的元字符。 Specifically, they group portions of the matched string. 具体来说,它们将匹配字符串的部分分组。 Thus, your regular expression (test) matched the substring "test". 因此,您的正则表达式(test)与子字符串“ test”匹配。 The return value gives you the entire match as the first element of the array, and the first group as the second. 返回值使您将整个匹配项作为数组的第一个元素,将第一个组作为第二个元素。 In this case, because your group covered the whole matched substring, they're the same. 在这种情况下,因为您的组覆盖了整个匹配的子字符串,所以它们是相同的。

This is the sort of thing that the MDN documentation can quickly clear up: MDN文档可以快速清除这种情况:

Parameters 参量

regexp 正则表达式
A regular expression object. 正则表达式对象。 If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). 如果传递了非RegExp对象obj,则使用新的RegExp(obj)将其隐式转换为RegExp。

You have to do this: 您必须这样做:

temp = '\(test\)';
temp.match(temp);

Since () define groups in Regex. 由于()在正则表达式中定义了组。 look here for more info: http://www.regular-expressions.info/brackets.html 在这里查看更多信息: http : //www.regular-expressions.info/brackets.html

The () are characters used by regex. ()是正则表达式使用的字符。 Just like .*[] etc. That's why it does not return the (). 就像。* []等一样。这就是为什么它不返回()的原因。 What I've done in the example above is escape them. 在上面的示例中,我所做的就是逃避它们。 So the Regex does not see it as a grouping. 因此,正则表达式不将其视为分组。

Update: 更新:

it does work this way: 它确实以这种方式工作:

"(test)".match(/\(test\)/);

When you create a String and have a different Regex Object. 创建字符串并具有其他正则表达式对象时。

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

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