简体   繁体   中英

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 .

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):

/\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:

(?=[.,]|\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).

Note that this will also match constructions like '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).

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. Note that you would need to check if the conversion worked with the Number.isNaN function.

Another possibility is to just use the parseFloat function. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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