Why does this regular expression also match words inside a non-capture group?

I have this line (note the multi-line syntax):

var str = ` Number One: Get this Number Two: And this`; 

And I want the returned regular expression (with match ):

 [str, 'Get this', 'And this'] 

So, I tried str.match(/Number (?:One|Two): (.*)/g); , but return:

 ["Number One: Get this", "Number Two: And this"] 

Any word "Number" can be preceded by any spaces / line breaks.

Why doesn't he only return what is inside the capture group? Am I distorting something? And how can I achieve the desired result?

+6
source share
3 answers

Per MDN documentation for String.match :

If the regular expression includes the g flag, the method returns an Array containing all matched substrings, not matching objects. Captured groups are not returned. If there were no matches, the method returns null .

(a main attention).

So you do not want.

On the same page is added:

  • if you want to get capture groups and the global flag is set, you need to use RegExp.exec() instead.

therefore, if you are ready to refuse to use match , you can write your own function that re-applies the regular expression, gets the captured substrings and creates an array.


Or, for your specific case, you could write something like this:

 var these = str.split(/(?:^|\n)\s*Number (?:One|Two): /); these[0] = str; 
+4
source

Try

  var str = " Number One: Get this\ Number Two: And this"; // `/\w+\s+\w+(?=\s|$)/g` match one or more alphanumeric characters , // followed by one or more space characters , // followed by one or more alphanumeric characters , // if following space or end of input , set `g` flag // return `res` array `["Get this", "And this"]` var res = str.match(/\w+\s+\w+(?=\s|$)/g); document.write(JSON.stringify(res)); 
+2
source

Replace and save the result in a new line, for example:

 var str = ` Number One: Get this Number Two: And this`; var output = str.replace(/Number (?:One|Two): (.*)/g, "$1"); console.log(output); 

which outputs:

 Get this And this 

If you need an array of matches, as you requested, you can try the following:

 var getMatch = function(string, split, regex) { var match = string.replace(regex, "$1" + split); match = match.split(split); match = match.reverse(); match.push(string); match = match.reverse(); match.pop(); return match; } var str = ` Number One: Get this Number Two: And this`; var regex = /Number (?:One|Two): (.*)/g; var match = getMatch(str, "#!SPLIT!#", regex); console.log(match); 

which displays the array as desired:

 [ ' Number One: Get this\n Number Two: And this', ' Get this', '\n And this' ] 

If split (here #!SPLIT!# ) Should be a unique string to separate matches. Please note that this only works for specific groups. For multiple groups, add a variable indicating the number of groups, and add a loop construction for "$1 $2 $3 $4 ..." + split .

+2
source

Source: https://habr.com/ru/post/987890/


All Articles