0

Why does this regex return an entirely different result in javascript as compared to an on-line regex tester, found at http://www.gskinner.com/RegExr/

var patt = new RegExp(/\D([0-9]*)/g);
"/144444455".match(patt);

The return in the console is:

["/144444455"]

While it does return the correct group in the regexr tester.

All I'm trying to do is extract the first amount inside a piece of text. Regardless if that text starts with a "/" or has a bunch of other useless information.

2
  • Show us some example input with expected result. Commented Sep 20, 2012 at 14:42
  • Regular expressions engines are not all the same, the built-in regex libraries vary by language. That online one uses the ActionScript 3 built-in library, as it is written in Flex/Flash. That is not the same as the one used by Javascript. Commented Sep 20, 2012 at 14:43

1 Answer 1

3

The regex does exactly what you tell it to:

  • \D matches a non-digit (in this case /)
  • [0-9]* matches a string of digits (144444455)

You will need to access the content of the first capturing group:

var match = patt.exec(subject);
if (match != null) {
    result = match[1];
}

Or simply drop the \D entirely - I'm not sure why you think you need it in the first place...

Then, you should probably remove the /g modifier if you only want to match the first number, not all numbers in your text. So,

result = subject.match(/\d+/);

should work just as well.

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

1 Comment

You beat me to it, was just about to answer. :)

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.