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

Get all prices with $ from string into an array in Javascript

var string = 'Our Prices are 5.00 and 0, down form 9.00';

如何将这 3 个价格放入数组中?

使用 matchregex 如下:

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

正则表达式解释

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

Demo

这将检查 '$'

后是否有 可能的 十进制数字

正则表达式

string.match(/$((?:\d|\,)*\.?\d+)/g) || []

|| [] 不匹配:它给出一个空数组而不是 null

匹配

  • </code></li> <li><code>$.99
  • .99
  • ,999
  • ,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*)。这意味着,从技术上讲,像 9 这样的字符串与 second 数字(可选小数点后)匹配,这对结果无关紧要 —— 这只是一个技术问题。

非正则表达式方法:拆分字符串并过滤内容:

var arr = string.split(' ').filter(function(val) {return val.startsWith('$');});