Javascript Regex to Extract a Number -
i have strings such as
(123)abc defg(456) hijkl (999) 7
i want match these strings 1 @ time regular expression extract number string string starts '(' has number in between , ')' followed 0 or more characters. so, in above 5 examples match 123 in first case, nothing in second , third case, 999 in fourth case , nothing in fifth case.
i have tried this
var regex = new regexp("^\((\d+)\)", "gm"); var matches = str.match(regex);
but matches comes out null. doing wrong?
i have tried regex @ regex101 , seems work @ loss why code doesn't work.
you need push result of capturing group array, use exec()
method.
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' ]
Comments
Post a Comment