0

I am having some trouble with my regex in javascript. I have the following code, that I think should match, but it doesn't.

var rgx = new RegExp("{\d+:(\d+)}"); if (rgx.test("{0:00000}") == true) { alert("match"); } else { alert("no match"); } 

​I am unsure if I should use test() here. I really want to catch the group, in my regex but exec() seems to give me the same result.

So what am I doing wrong?

1
  • You might want to use ^ at the beginning and $ at the end as well, to make sure the string matches completely and not a substring - but that's up to you. Commented Nov 26, 2012 at 6:51

2 Answers 2

5

The problem is that you need to escape the \ character in your regex:

var rgx = new RegExp("{\\d+:(\\d+)}"); 

Alternatively, you can use the literal syntax:

var rgx = /{\d+:(\d+)}/; 

To capture the results, you should also use the .match function as opposed to test or exec. It will return null if it doesn't match and an array of at least one element if it does match.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the literal syntax. The RegExp constructor is rarely necessary and is confusing with all of the escaping necessary.
0

There are multiple issues with the regex:

var rgx = new RegExp("{\d+:(\d+)}"); 

First (first noted by syazdani), you must string-escape the backslashes:

var rgx = new RegExp("{\\d+:(\\d+)}"); 

or better yet use a regex literal:

var rgx = /{\d+:(\d+)}/ 

Second, { and } have a special meaning in regex and should be escaped:

var rgx = /\{\d+:(\d+)\}/ 

Third, as noted by Ian, you might want to ensure the entire string is matched:

var rgx = /^\{\d+:(\d+)\}$/ 

RegExp#test returns a boolean true/false whether the string matches.

RegExp#exec returns an array holding the match and all captured groups if the string is matched, or null if the string is not matched:

var matches = /\{\d+:(\d+)\}/.exec("{0:000000}"); if(matches){ console.log(matches[1]); //logs "000000" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.