[英]Get all prices with $ from string into an array in Javascript
var string = 'Our Prices are $355.00 and $550, down form $999.00';
如何将这3个价格组合在一起?
string.match(/\$((?:\d|\,)*\.?\d+)/g) || []
那|| []
|| []
没有匹配项:它给出一个空数组而不是null
。
$99
$.99
$9.99
$9,999
$9,999.99
/ # Start RegEx
\$ # $ (dollar sign)
( # Capturing group (this is what you’re looking for)
(?: # Non-capturing group (these numbers or commas aren’t the only thing you’re looking for)
\d # Number
| # OR
\, # , (comma)
)* # Repeat any number of times, as many times as possible
\.? # . (dot), repeated at most once, as many times as possible
\d+ # Number, repeated at least once, as many times as possible
)
/ # End RegEx
g # Match all occurances (global)
为了更轻松地匹配.99
数字,我使第二个数字为必需( \\d+
),同时使第一个数字(连同逗号)为可选( \\d*
)。 从技术上讲,这意味着像$999
这样的字符串与第二个数字(在可选的小数点之后)匹配,这与结果无关紧要–只是技术上的问题。
非正则表达式方法:拆分字符串并过滤内容:
var arr = string.split(' ').filter(function(val) {return val.startsWith('$');});
使用match
与regex
,如下所示:
string.match(/\$\d+(\.\d+)?/g)
正则表达式说明
/
: regex
分隔符 \\$
:匹配$
文字 \\d+
:匹配一个或多个数字 ()?
:匹配零个或多个前面的元素 \\.
:火柴.
g
:匹配所有可能的匹配字符 这将检查在“ $”之后是否存在可能的十进制数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.