3

I have strings such as

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

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

I have tried this

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

But matches always comes out as null. What am I doing wrong?

I have tried this regex at regex101 and it seems to work so I am at a loss why the code doesn't work.

asked Jun 14, 2015 at 16:25
1
  • When using the RegExp constructor, you'll need to provide escape sequences for both the pattern and the string literal -- new RegExp("^\\((\\d+)\\)", "gm"). Commented Jun 14, 2015 at 16:28

3 Answers 3

3

You need to push the result of the capturing group to an array, for this use the 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' ]
answered Jun 14, 2015 at 16:33
Sign up to request clarification or add additional context in comments.

Comments

3

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 in his comment you have to escape backslashes when you use RegExp:

new RegExp("^\\((\\d+)\\)", "gm")
answered Jun 14, 2015 at 16:27

Comments

2

You can use this regex:

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

and use captured group #1

RegEx Demo

Using regex constructor (note double escaping):

var regex = new RegExp("^\\((\\d+)(?=\\))", "gm");
answered Jun 14, 2015 at 16:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.