Javascript Regex to extract number

I have lines like

(123)abc
defg(456)
hijkl
(999)
7

      

I want to match these strings one at a time with a regex to extract any number from a string where the string starts with '(' has a number between and then and ')' followed by zero or more characters.So in the examples above I would match 123 in the first case, nothing in the second and third cases, 999 in the fourth case, and nothing in the fifth case.

I tried this

var regex = new RegExp("^\((\d+)\)", "gm");
var matches = str.match(regex);

      

But matches are always reported as null. What am I doing wrong?

I tried this regex in regex101 and it seems to work, so I don't understand why the code is not working.

+3


source to share


3 answers


You need to push the result of the capturing group onto the array, for that use the method exec()

.



var str = '(123)abc\ndefg(456)\nhijkl\n(999)\n7'
var re  = /^\((\d+)\)/gm, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}

console.log(matches) //=> [ '123', '999' ]

      

+3


source


I don't see anything wrong with your regex, try this code generated from regex101:

var re = /^\((\d+)\)/gm; 
var str = '(123)abc\ndefg(456)\nhijkl\n(999)\n7';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

      

Working demo



Btw, as jonathan lonowski pointed out in his comment, that you should avoid backslashes when using RegExp:

new RegExp("^\\((\\d+)\\)", "gm")

      

+3


source


You can use this regex:

var regex = /^\((\d+)(?=\))/gm;

      

and use captured group # 1

Demo version of RegEx

Using the regex constructor (note the double escaping):

var regex = new RegExp("^\\((\\d+)(?=\\))", "gm");

      

+2


source







All Articles