从javascript中的字符串中提取所有数字

syl*_*mos 3 javascript regex

我想要给定字符串中所有正确的自然数,

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

在上面的字符串中我应该只匹配第一个单词5等中的数字12,34,5,67,而不是1234.

所以数字应该等于[12,34,5,67]

Avi*_*Raj 7

使用单词边界,

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

说明:

  • \b在单词charcter(\w)和非单词charcter(\W)之间匹配的单词边界.
  • \d+ 一个或多个数字.
  • \b 在单词字符和非单词字符之间匹配的单词边界.

要么

> 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' ]
Run Code Online (Sandbox Code Playgroud)

代码从这里被盗.

  • @syllogismos不,它是单词和非单词字符之间的零宽度匹配(按任意顺序),请参阅http://www.regular-expressions.info/wordboundaries.html.@ j08691 - 只要你不想匹配`something123`中的`123`就需要它. (2认同)