Extract all numbers from string in javascript

I want all the corresponding natural numbers from a given string to be

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

      

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

therefore the numbers must be equal [12,34,5,67]

+3


source to share


2 answers


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

    a word boundary that matches between the word charcter ( \w

    ) and the non- leading character ( \w

    ).
  • \d+

    One or more numbers.
  • \b

    a word boundary that matches between a charcter word character and a non-principal character.


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' ]

      

The code is stolen from here .

+7


source


If anyone is interested in a proper regular solution for matching digits surrounded by whitespace characters, it's just for languages ​​that support lookbehind (like Perl and Python, but not JavaScript at the time of writing):

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

      

Regular expression visualizationDebuggex PCRE Demo

As shown in the accepted answer, in languages ​​that don't support lookbehind, a hack must be used, e.g. to enable 1st place in a match while keepingting important things in the capture group:



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

      

Regular expression visualizationJavaScript Debuggex Demo

Then you just need to extract that capturing group from the matches, see for example this answer on How to access matched groups in a JavaScript regex?

+2


source







All Articles