首页 > 解决方案 > 使用正则表达式从字符串中获取不同格式的数字

问题描述

我需要从字符串中获取这些数字格式

20000
20 000
20 000 000
20 000,00
20 000.00
2000,000
200000.000

字符串可以

some text 20000
20000 some text 

到目前为止我有这个

/((\d){1,}[ .,]{1}[0-9]{1,}[ .,]{1}[0-9]{1,})/g

谢谢你。

标签: regex

解决方案


我会使用这个正则表达式:

^[1-9][0-9]{0,2}(?:[ ,]?\d{3})*(?:[,.]\d+)?$

演示

这是正则表达式的解释:

^                from the start of the string
[1-9][0-9]{0,2}  match 1 to 3 leading digits (first digit not zero)
(?:[ ,]?\d{3})*  then match an optional thousands separator followed by 3 digits,
                 the entire quantity zero or more times
(?:[,.]\d+)?     match an optional decimal component, using either , or . as the separator
$                end of the string

推荐阅读