Get price (amount only, no currency tag, no special characters) from String via RegEx

Viewed 72

I have written a RegEx syntax which also works, but I fear I am missing something or maybe there is a more elegant way too achieve what I need.

Link: https://regex101.com/r/KZxt9I/1

enter image description here

Goal is to get whatever price there is before the term "EUR":

  1. Sometimes the price is written like the first match -> integer (no Cents)
  2. Sometimes the price is written like the second match -> double (with comma due to Cents)

As you can see in the first match there is also ",-" before "EUR" and in the second match the string does not have ",-" before "EUR".

Is my RegEx sufficient enough in case there are more whitespaces inbetween or so?

1 Answers

Your regex is too complicated, you can make it much simpler:

^Preis$\s*(\d+(?:,\d+)?).*EUR
^Preis$\s*(\d+(?:,\d+)?)\W*EUR

See the regex demo. Note that you only need one capturing group and the rest can be written as consuming patterns as you will extract the contents of Group 1 anyway.

The difference between the two is \W* and .*, \W* matching any zero or more non-word chars while .* matching any zero or more chars other than line break chars as many as possible.

The \s* you used matches any zero or more whitespace chars, so you should not worry about how many whitespace chars there are between Preis and the number.

If you need to make sure EUR is matched as a whole word, add \b right after:

^Preis$\s*(\d+(?:,\d+)?)\W*EUR\b

Details:

  • ^ - start of string (or line if RegEx.Multiline is True)
  • Preis - a word
  • $ - end of string/line
  • \s* - zero or more whitespace chars
  • (\d+(?:,\d+)?) - Capturing group 1: one or more digiots and then an optional occurrence of a comma and one or more digits
  • \W* - zero or more non-word chars as many as possible
  • EUR\b - EUR as a whole word.
Related