regex to split number from string

浪子不回头ぞ 提交于 2019-12-06 06:47:11

问题


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

30/kg

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?


回答1:


The lookarounds are completely unnecessary here!

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

The code:

var text = "1dozen 3 dozen dozen1 30/kg";
var regex = /(\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.




回答2:


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


来源:https://stackoverflow.com/questions/7857513/regex-to-split-number-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!