简体   繁体   English

javascript正则表达式浮点数,以字符串结尾

[英]javascript regex float number which ends with string

Learning regex but this one gives me a headache. 学习正则表达式,但这让我头疼。 I need to match a float number (with either . or , as decimal point) and it MUST end with the following characters: €/g . 我需要匹配一个浮点数(以.,作为小数点),并且必须以以下字符结尾: €/g

Valid matches should be for example: 有效匹配应为例如:

  • 40€/g
  • 43.33€/g
  • 40,2€/g
  • 40.2€/g
  • 38.943€/g

Appreciate help.. 感谢帮助。

The regex will look like: 正则表达式如下所示:

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

In Javascript, as a regex object (note that the forward slash needs to be escaped): 在Javascript中,作为正则表达式对象(请注意,正斜杠需要转义):

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

Here's a breakdown of what each part does: 以下是每个部分的功能细分:

\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

If you want to allow something like .123€/g to be valid as well, you can use: 如果您还想允许.123€/ g之类的内容有效,则可以使用:

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

That is, both the groups of digits are optional, but at least one must be present (this uses lookahead , which is a bit more tricky). 也就是说,两组数字都是可选的,但是必须至少存在一个数字(这使用lookahead ,这比较棘手)。

Note that this will also match constructions like 'word2€/g'. 请注意,这还将匹配“ word2€/ g”之类的构造。 If you want to prevent this, start the regex with (?<=^|\\s) (matches if preceded by a space or the start of the string) and end it with (?=$|\\s) (matches if followed by a space or the end of the string). 如果要防止这种情况,请以(?<=^|\\s) (如果以空格或字符串开头开头,则匹配正则表达式),然后以(?=$|\\s) (以空格开头,则匹配)结尾空格或字符串的结尾)。

Full-blown version: 完整版:

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

我想应该会起作用。

Are you really sure you need a regex for this? 您确定要为此使用正则表达式吗? It might be easier to instead leverage the builtin floating point parsing that is available: take whatever comes before the euro sign, normalize commas to decimals (or vice versa, whatever ends up working) and then try to parse it with the Number function. 相反,利用可用的内置浮点解析可能会更容易:采用欧元符号之前的任何内容,将逗号规范化为小数(反之亦然,无论结果如何),然后尝试使用Number函数进行解析。 Note that you would need to check if the conversion worked with the Number.isNaN function. 请注意,您需要检查转换是否与Number.isNaN函数一起使用。

Another possibility is to just use the parseFloat function. 另一种可能性是仅使用parseFloat函数。 Since it ignores any characters after the numbers then it would parse "40€ as 40.0 . However, it might not be what you want since it would also allow things like "40a" and "40b" as well. 由于它会忽略数字后面的任何字符,因此它将解析"40€ as 40.0 。但是,它可能不是您想要的,因为它也允许"40a""40b"类的东西。

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

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