javascript 正则表达式从字符串中拆分数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7857513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:33:07  来源:igfitidea点击:

regex to split number from string

javascriptregexstringnumbers

提问by alucard

How to split and select which is number using regex. User can enter string like:

如何使用正则表达式拆分和选择哪个数字。用户可以输入如下字符串:

1dozen 3 dozen dozen1 <= unlikely but assume user will type that too

1 打 3 打打 1 <= 不太可能但假设用户也会输入

30/kg

30/公斤

I still find out with the incomplete one:

我仍然发现不完整的:

/[a-z](?=\d)|\d(?=[a-z])/i

But missing space and forward slash. Can anyone help me?

但缺少空格和正斜杠。谁能帮我?

回答by Ray Toal

The lookarounds are completely unnecessary here!

这里完全不需要环视!

See http://jsfiddle.net/5WJ9v/

http://jsfiddle.net/5WJ9v/

The code:

代码:

var text = "1dozen 3 dozen dozen1 30/kg";
var regex = /(\d+\.|\d+)+/g;
alert(text.match(regex));

You get a match object with all of your numbers.

您会得到一个包含所有号码的匹配对象。

The script above correctly alerts 1,3,1,30.

上面的脚本正确地发出警报1,3,1,30

回答by Sahil Muthoo

var str = '1dozen 3 dozen dozen1 30/kg';
str.match(/\d+/g); // ["1", "3", "1", "30"]