syllogismos
syllogismos

Reputation: 660

extract all the numbers from a string in a javascript

I want all the proper natural numbers from a given string,

var a = "@1234abc 12 34 5 67 sta5ck over @ numbrs ."
numbers = a.match(/d+/gi)

in the above string I should only match the numbers 12, 34, 5, 67, not 1234 from the first word 5 etc..

so numbers should be equal to [12,34,5,67]

Upvotes: 4

Views: 305

Answers (2)

Aprillion
Aprillion

Reputation: 22304

If anyone is interested in a proper regex solution to match digits surrounded by space characters, it is simple for languages that support lookbehind (like Perl and Python, but not JavaScript at the time of writing):

(?<=^|\s)\d+(?=\s|$)

Regular expression visualization Debuggex PCRE Demo

As illustrated in the accepted answer, in languages that don't support lookbehind, it is necessary to use a hack, e.g. to include the 1st space in the match, while keepting the important stuff in a capturing group:

(?:^|\s)(\d+)(?=\s|$)

Regular expression visualization Debuggex JavaScript Demo

Then you just need to extract that capturing group from the matches, see e.g. this answer to How do you access the matched groups in a JavaScript regular expression?

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174696

Use word boundaries,

> var a = "@1234abc 12 34 5 67 sta5ck over @ numbrs ."
undefined
> numbers = a.match(/\b\d+\b/g)
[ '12', '34', '5', '67' ]

Explanation:

  • \b Word boundary which matches between a word charcter(\w) and a non-word charcter(\W).
  • \d+ One or more numbers.
  • \b Word boundary which matches between a word charcter and a non-word charcter.

OR

> var myString = '@1234abc 12 34 5 67 sta5ck over @ numbrs .';
undefined
> var myRegEx = /(?:^| )(\d+)(?= |$)/g;
undefined
> function getMatches(string, regex, index) {
...     index || (index = 1); // default to the first capturing group
...     var matches = [];
...     var match;
...     while (match = regex.exec(string)) {
.....         matches.push(match[index]);
.....     }
...     return matches;
... }
undefined
> var matches = getMatches(myString, myRegEx, 1);
undefined
> matches
[ '12', '34', '5', '67' ]

Code stolen from here.

Upvotes: 8

Related Questions