Search code examples
regexcurrency

Regex to extract UK Currency including £ symbol and Pence (p)


I am fairly new to RegEx and have had a search around online but am unable to find a regex that fits my requirements.

The ultimate aim is to search a string of text and extract the lowest monetary amount, however as the string may contain more than one £amount, then i'm happy for a regex to just extract all monetary values it can find and then I can write a calculation in order to return the lowest amount.

The string may have numbers that are not monetary values / numerous amounts, therefore the regex should always look for a £ symbol first OR it could end with a "p" or "P" to signify pence. For example "I need 2 of these at £10 each and one of those at 50p" - should return 10.00 & 0.50 - I can then calculate that 0.50 is the lowest amount.

As people also write their amounts in various ways, I need the regex to be able to spot different patterns - including the "," for every thousand. All below values should be valid:

£0
£0.00
£0.00p
£0000
£0000.00
£0000.00p
£0,000
£0,000.00
£0,000.00p
0p

Hopefully someone may be able to advise the best way to approach this.

Thanks


Solution

  • This works on your data set:

    (?=^£|.*p$)£?\d*(?:,\d{3})*(\.\d{2})?p?
    

    But it may improperly match some edge cases as well because everything is optional...

    https://regex101.com/r/WptUn6/3