繁体   English   中英

使用字符串将$的所有价格从字符串获取到数组中

[英]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('$');});

使用matchregex ,如下所示:

string.match(/\$\d+(\.\d+)?/g)

正则表达式说明

  1. /regex分隔符
  2. \\$ :匹配$文字
  3. \\d+ :匹配一个或多个数字
  4. ()? :匹配零个或多个前面的元素
  5. \\. :火柴.
  6. g :匹配所有可能的匹配字符

演示版

这将检查在“ $”之后是否存在可能的十进制数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM