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
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.
}
Btw, as jonathan lonowski pointed out in his comment, that you should avoid backslashes when using RegExp:
new RegExp("^\\((\\d+)\\)", "gm")
+3
source to share