简体   繁体   English

正则表达式javascript不返回括号

[英]regex javascript doesn't return parenthesis

When I am trying to do my regex in js: 当我尝试在js中执行正则表达式时:

 var matc = source.match(/sometext(\\d+)/g); 

The result I get is "sometext5615", "sometext5616"...etc But what I want: is to get "5615", "5616"...etc 我得到的结果是“ sometext5615”,“ sometext5616” ...等,但是我想要的是:得到“ 5615”,“ 5616” ...等

Do you have any idea how to get only what is inside the parenthese ? 您是否知道如何仅获取括号内的内容?

String.prototype.match has two different behaviors: String.prototype.match具有两种不同的行为:

  • If the regex doesn't have the global g flag, it returns regex.exec(str) . 如果正则表达式没有全局g标志,则返回regex.exec(str) That means that, if there is a match, you will get an array where the 0 key is the match, the key 1 is the first capture group, the 2 key is the second capture group, and so on. 这意味着,如果存在匹配项,您将得到一个数组,其中0键是匹配项,键1是第一个捕获组,键2是第二个捕获组,依此类推。

  • If the regex has the global g flag, it returns am array with all matches, but without the capturing groups. 如果正则表达式具有全局g标志,则它将返回具有所有匹配项但没有捕获组的am数组。

Therefore, if you didn't use the global flag g , you could use the following to get the first capture group 因此,如果您不使用全局标志g ,则可以使用以下命令获取第一个捕获组

var matc = (source.match(/sometext(\d+)/) || [])[1];

However, since you use the global flag, you must iterate all matches manually: 但是,由于使用了全局标志,因此必须手动迭代所有匹配项:

var rg = /sometext(\d+)/g,
    match;
while(match = rg.exec(source)) {
    match[1]; // Do something with it, e.g. push it to an array
}

JavaScript does not have a "match all" for global matches, so you cannot use g in this context and also have capture groups. JavaScript的全局匹配没有“全部匹配”,因此您不能在这种情况下使用g并且还具有捕获组。 The simplest solution would be to remove the g and then just use matc[1] to get 5615, etc. 最简单的解决方案是删除g ,然后仅使用matc[1]获得5615,依此类推。

If you need to match multiple of these within the same string then your best bet would be to do a "search and don't replace" 如果您需要在同一字符串中匹配多个,那么最好的选择是进行“搜索且不要替换”

var matc = [];
source.replace(/sometext(\d+)/g, function (_, num) {
    matc.push(num);
});

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

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