Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用split方法通过正则表达式从字符串中收集数字_Javascript_Regex - Fatal编程技术网

Javascript 使用split方法通过正则表达式从字符串中收集数字

Javascript 使用split方法通过正则表达式从字符串中收集数字,javascript,regex,Javascript,Regex,我喜欢将数字从字符串收集到数组中。我尝试了下面的方法,但在Javascript中并没有得到预期的结果。我该怎么做 'This is string 9, that con 9 some 12, number rally awesome 8'.split(/[^\d+]/); 我想这不是斯威夫特 'This is string 9, that con 9 some 12, number rally awesome 8 extra'. split(/[^\d]+/); 产生 [ '', '9',

我喜欢将数字从字符串收集到数组中。我尝试了下面的方法,但在Javascript中并没有得到预期的结果。我该怎么做

'This is string 9, that con 9 some 12, number rally awesome 8'.split(/[^\d+]/);

我想这不是斯威夫特

'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/);
产生

[ '', '9', '9', '12', '8', '' ]
正如您所看到的,它在大多数情况下都可以到达那里,但是可能有一个前导和尾随的空字符串

过滤器可以解决这个问题

'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/).
filter(function(number) { return number.length > 0 });
生成您正在寻找的答案

[ '9', '9', '12', '8' ]
或者如果您正在使用ES6

'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/).
filter(number => number.length > 0);

你的regex托管语言是什么?这看起来与
NSRegularExpression
无关,
+
不是您想要匹配的字符,我想,试试
/[^\d]+/
(但第一个数组元素为空,如果将文本放在8后面,最后一个数组元素也是空的)@dasblinkenlight是的,这是我的错误。它应该是/[^\d]+/为什么不直接使用
\d+
?它会帮你解决所有的问题numbers@ctwheels实际上,我们希望通过JavaScript拆分方法来实现这一点。