简体   繁体   English

为什么此RegExp匹配两个字符串?

[英]Why does this RegExp match two strings?

var str = "abcd1234";
var first = str.match(/^abcd(\d+)$/)[0]; //matches abcd1234
var number = str.match(/^abcd(\d+)$/)[1]; //matches 1234 only

Why does this regex first match the whole of str and then match the numeric part? 为什么此正则表达式首先匹配整个str ,然后匹配数字部分? Looking at it I'd say it would always have to match abcd and then 1 or more digits? 看着它,我会说它总是必须匹配abcd ,然后再匹配1个或多个数字? Isn't the 'abcd' a mandatory part of the match? “ abcd”不是比赛的强制性部分吗?

Incidentally I found this regex as part of this question . 偶然地,我发现这个正则表达式是这个问题的一部分。

Thanks. 谢谢。

It's because 0 refers to the whole match while 1 refers to the first parenthezised group (which is actually 1234) 这是因为0代表整个比赛,而1代表第一个括号组(实际上是1234)

You could have this for example: 您可能有以下示例:

var str = "abcd1234";
var first = str.match(/^(abcd)(\d+)$/)[0]; //returns abcd1234
var chars = str.match(/^(abcd)(\d+)$/)[1]; //returns abcd only
var number = str.match(/^(abcd)(\d+)$/)[2]; //returns 1234 only

It is normal in regex match results for [0] to be the whole match. 正则表达式匹配结果中的正常情况是[0]是整个匹配。 and then [1]...etc. 然后[1] ...等 to contain the partial matches. 包含部分匹配项。 If you want both first and second part from the match, you will need to write something like: 如果您想要比赛的第一部分和第二部分,则需要编写如下内容:

  var m = str.match(/^(abcd)(\d+)$/);
  var wholematch = m[0];
  var first = m[1];
  var num = m[2];

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/RegExp

The capturing parentheses store the match from that part of the regex and hold it separate from the first result, which is the whole match. 捕获括号将匹配项存储在正则表达式的该部分中,并将其与第一个结果(即整个匹配项)分开保存。

Any part of your regex in brackets '( )' becomes a grouping. 方括号“()”中的正则表达式的任何部分都将成为一个分组。 This portion of the match is then also returned when you match your regex. 当您匹配正则表达式时,也将返回匹配的这一部分。 This can be useful if you want to match a pattern and then use different parts of it for processing (eg a list of key value pairs in the format "key:value" you could make a group for key and for the value). 如果要匹配模式然后使用模式的不同部分进行处理(例如,可以将键和值的格式划分为“键:值”格式的键值对列表),这将很有用。

You can make a grouping non capturing by placing ' ?: ' after the first bracket. 您可以通过在第一个方括号后放置' ?: '来使分组无法捕获 The following will match your regex and not capture the grouping/brackets part: 以下内容将与您的正则表达式匹配,但不会捕获分组/括号部分:

var first = str.match(/^abcd(?:\d+)$/)[0]; //returns abcd1234 ONLY

Also gskinner has a nice regex tester that will show you the groupings for your regex (hover over blue highlighted text). 此外,gskinner还有一个不错的正则表达式测试器 ,它将为您显示正则表达式的分组(将鼠标悬停在蓝色突​​出显示的文本上)。

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

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