javascript 如何仅匹配前面带有货币符号(如“$”)的成本或价格编号值?

2nbm6dog  于 2023-02-11  发布在  Java
关注(0)|答案(4)|浏览(131)

It will cost you $112.52 for 302 pokemon cards to complete this order
It will cost you $112.52 to complete this order
上面是我想用正则表达式找到美元值的两个字符串。下面是我现在使用的正则表达式:
const match = str.match(/will cost you \$(.*) for ([0-9]+) pokemon cards to complete this order|will cost you \$(.*) to complete this order/);
我可以在match[1]和match[3]中得到两个字符串的$112.52
然而,使用这种方法(([0-9]+)),我也匹配了口袋妖怪卡片的数量302,这不是我想要的(在match[2]中)。有没有一种方法可以忽略任何数量的口袋妖怪卡片,只匹配一个正则表达式中两个字符串中的美元符号值?

vdgimpew

vdgimpew1#

如果你只想得到美元金额,而不关心字符串中的其他任何东西,你就不需要在正则表达式中提到字符串中的其他任何东西。
你可以只匹配$后面跟数字和点,即

str.match(/\$([\d\.]+)/)

更完整的测试示例...

(function() {
    let strs = [
        "It will cost you $112.52 for 302 pokemon cards to complete this order",
        "It will cost you $112.52 to complete this order"
    ];
    
    strs.forEach(
        (str) => {
            let match = str.match(/\$([\d\.]+)/);
            console.debug(match);
        }
    );
})();

...输出...

Array [ "$112.52", "112.52" ]
Array [ "$112.52", "112.52" ]
7dl7o3gd

7dl7o3gd2#

一个精确匹配的正则表达式还必须检查前导$后面的数值的有效性。可以通过正则表达式循环来实现这一点,其中负的前向查找将确保单个有效的整数或浮点数值,而正的后向查找将支持数值的直接match
这样的正则表达式如下所示...

/(?<=\$)(?:\d*\.)?\d+(?![.\d])/g

...和the description is provided by its test/playground page
它的用法如下...
x一个一个一个一个x一个一个二个x
由于lookbehinds are not supported by e.g. even the latest safari versions,必须解决它。一个可能的解决方案是使用一个例如命名的捕获组。
上面首先提供regex,然后更改为...

/\$(?<value>(?:\d*\.)?\d+)(?![.\d])/g

...其中the pattern gets explained by its test/playground page
它的用法也需要更改,从match更改为matchAll,然后执行额外的map ping任务...

const sampleText = `
  It will cost you $112.52 for 302 pokemon cards to complete this order
  It will cost you $.52 for 302 pokemon cards to complete this order

  It will cost you $2.52.523.45 for 302 pokemon cards to complete this order
  It will cost you $.52.523.455 for 302 pokemon cards to complete this order
  It will cost you $ .52 to complete this order

  It will cost you $.52 to complete this order
  It will cost you $112 to complete this order`;

// see ... [https://regex101.com/r/hjIoWb/2]
const regXNumberValue = /\$(?<value>(?:\d*\.)?\d+)(?![.\d])/g;

console.log(
  [...sampleText.matchAll(regXNumberValue)]
    .map(({ groups: { value } }) => value)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
laximzn5

laximzn53#

在正则表达式中使用lookbehindAssert
(?〈= Y)X如果在Y之后,则为正后视X
(?<=\$)\d+
示例:https://regex101.com/r/H7Iyb6/1
参考:https://javascript.info/regexp-lookahead-lookbehind
另一种方法是,您可以将unicode属性\p类与\u标志一起使用

const regex = \p{Sc}\p{Nd}+.\p{Nd}+

\p example

yhived7q

yhived7q4#

你在https://regex101.com/上试过正则表达式吗?
我发现这个解决方案后,尝试这个网站:
(will完成此订单需要([0-9]+)张口袋妖怪卡$(.)|完成此订单将花费$(.))
它会把你的价格到组2和卡的数量到组3

相关问题