12

So, I'm trying to write a regex that matches all numbers. Here is that regex:

/\b[\d \.]+\b/g

And I try to use it on the string:

100 two 100

And everything works fine; it matches both of the numbers.

But I want to rewrite the regex in the form:

new RegExp(pattern,modifiers)

Because I think it looks clearer. So I write it like this:

new RegExp('\b[\d \.]+\b','g')

But now it won't match the former test string. I have tried everything, but I just can't get it to work. What am I doing wrong?

0

1 Answer 1

18

Your problem is that the backslash in a string has a special meaning; if you want a backslash in your regexp, you first need to get literal backslashes in the string passed to the regex:

new RegExp('\\b[\\d \\.]+\\b','g');

Note that this is a pretty bad (permissive) regex, as it will match ". . . " as a 'number', or "1 1...3 42". Better might be:

/-?\d+(?:\.\d+)?\b/

enter image description here

Note that this matches odd things like 0000.3 also does not match:

  • Leading +
  • Scientific notation, e.g. 1.3e7
  • Missing leading digit, e.g. .4

Also, note that using the RegExp constructor is (marginally) slower and certainly less idiomatic than using a RegExp literal. Using it is only a good idea when you need to constructor your RegExp from supplied strings. Most anyone with more than passing familiarity with JavaScript will find the /.../ notation fully clear.

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

1 Comment

It is worth mentioning that you can use new RegExp(String.raw`\b[\d \.]+\b`, "g") instead of manually escaping each special character. Notice the backticks following String.raw instead of quotation marks.

Your Answer

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.