Node.js RegExp doesn't handle multiple matches for 'g' flag?

Is Javascript RegExp # exec () NOT handling multiple results with the 'g' flag? If not, what are the alternatives?

I have a line like this:

a*  2
b   3
c*  4

      

and I only want to extract the lines that have an asterisk. I wrote this regex:

/\w+\*\s+(\d+)\n/g

      

(i.e. matches a word, followed by a literal asterisk, followed by a space, followed by a digit capturing group, followed by a newline, and a global flag is turned on).

In the adorable https://regex101.com/#javascript, applying a string to regexp returns two matches as expected:

Match 1
1.   '2'
Match 2
1.   '4'

      

But in node.js I get this:

> match = re.exec(str)
> match
[ 'a*  2\n', '2', index: 0, input: 'a*  2\nb   3\nc*  4\n' ]

      

It looks like the match object is not multidimensional, or at least it only captures the first match.

Am I missing something fundamental? And (as I asked at the top) is there a reasonable alternative?

+3


source to share


2 answers


Javascript RegExp # exec () supports multiple matches, but does not return them at once. You must call exec () multiple times. The docs for this function on MDN explain the problem and give an example of using exec () on multiple matches. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Examples



var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

      

+1


source


I'll cover this in return, saying that I know very little about Regex, but I just did my own testing and found that the problem might be with \n

your regex.

The requirement \n

means that in a snippet like posted, if c* 4

there is no newline after , that row will not be matched.

\w+\*\s+(\d+)

works fine according to my tests on Regexr .

As I said, I may be a mile here, but that's just my thought.

Edit . My testing results:



/\w+\*\s+(\d+)\n/g

a*  2   [MATCH]
b   3
c*  4

      

and

/\w+\*\s+(\d+)/g

a*  2   [MATCH]
b   3
c*  4   [MATCH]

      

Using the original, but adding a new line after c

:

/\w+\*\s+(\d+)\n/g

a*  2   [MATCH]
b   3
c*  4   [MATCH]
\n

      

0


source







All Articles