Home > OS >  Regex: how to match a formatted number?
Regex: how to match a formatted number?

Time:01-03

I have written the following regex

(?<=\bUSD\s)([ -]?((\d \.?\d*)|(\.\d )))

It returns the number after a currency, so if we have 123.5 USD, it will return 123.5, it can be tested here

I want to make a few modifications to the regex, sometimes we receive numbers formatted like this:

  1. a ' formatted number USD 1’750.00
  2. or a space formatted number USD 1 753.00
  3. or a comma formatted number USD 1,753.00
  4. or the currency is after the number 1’750.00 USD
  5. I'd like the regex to return 2 values: the amount $1 and the currency $2
  6. It would be awesome also if the regex can support multiple currencies, but if not that's okay.

CodePudding user response:

(\d [’.,\s]\d [.]\d |\d [.,\s]\d )|(USD|CAD|CDF)

There are 2 groups:

  • (USD|CAD|CDF) matches a currency (here you can list different currencies)
  • (\d [’.,\s]\d [.]\d |\d [.,\s]\d ) matches numbers in different formats, covers all the cases with numbers you mentioned
    • \d [.,\s]\d matches numbers like 123.4
    • \d [’.,\s]\d [.]\d includes other cases like 1 753.00

regex101.com

  • Related