gpt4 book ai didi

以字符串结尾的javascript正则表达式 float

转载 作者:行者123 更新时间:2023-11-30 07:26:46 24 4
gpt4 key购买 nike

学习正则表达式,但这个让我头疼。我需要匹配一个 float (以 ., 作为小数点)并且它必须以以下字符结尾:€/g .

有效匹配应该是例如:

  • 40 欧元/克
  • 43.33€/g
  • 40,2€/g
  • 40.2€/g
  • 38.943€/g

感谢帮助..

最佳答案

正则表达式看起来像:

\d+(?:[.,]\d+)?€/g

在 Javascript 中,作为正则表达式对象(注意正斜杠需要转义):

/\d+(?:[.,]\d+)?€\/g/

以下是每个部分的功能分割:

\d+  # one or more digits
(?: # ... don't capture this group separately
[.,] # decimal point
\d+ # one or more digits
)? # make the group optional
€/g # fixed string to match

如果您希望 .123€/g 之类的值也有效,您可以使用:

(?=[.,]|\d)(?:\d+)?(?:[.,]\d+)?€/g

也就是说,两组数字都是可选的,但至少必须存在一个(这使用 lookahead ,这有点棘手)。

请注意,这也将匹配像“word2€/g”这样的结构。如果你想防止这种情况,请使用 (?<=^|\s) 启动正则表达式(如果前面有空格或字符串开头则匹配)并以 (?=$|\s) 结尾(如果后跟空格或字符串结尾则匹配)。

完整版:

(?<=^|\s)(?=[.,]|\d)(?:\d+)?(?:[.,]\d+)?€/g(?=$|\s)

关于以字符串结尾的javascript正则表达式 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11630231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com