简体   繁体   中英

UK Currency Regular Expression for javascript

I'm after a regular expression that matches a UK Currency (ie. £13.00, £9,999.99 and £12,333,333.02), but does not allow negative (-£2.17) or zero values (£0.00 or 0).

I've tried to create one myself, but I've got in a right muddle!

Any help greatfully received.

Thanks!

This'll do it (well mostly...)

/^£?[1-9]{1,3}(,\d{3})*(\.\d{2})?$/

Leverages the ^ and $ to make sure no negative or other character is in the string, and assumes that commas will be used. The pound symbol, and pence are optional.

edit: realised you said non-zero so replaced the first \\d with [1-9]

Update: it's been pointed out the above won't match £0.01. The below improvement will but now there's a level of complexity where it may quite possibly be better to test /[1-9]/ first and then the above - haven't benchmarked it.

/^£?(([1-9]{1,3}(,\d{3})*(\.\d{2})?)|(0\.[1-9]\d)|(0\.0[1-9]))$/

Brief explanation:

  • Match beginning of string followed by optional "£"
  • Then match either :
    • a >£1 amount with potential for comma separated groupings and optional pence
    • OR a <£1 >=£0.10 amount
    • OR a <=£0.09 amount
  • Then match end of line

The more fractions of pence (zero in the above) you require adding to the regex the less efficient it becomes.

Under Unix/Linux, it's not always possible to type in the '£' sign in a JavaScript file, so I tend to use its hexadecimal representation, thus:

/^\\xA3?\\d{1,3}?([,]\\d{3}|\\d)*?([.]\\d{1,2})?$/

This seems to take care of all combinations of UK currency amounts representation that I have come across.

/^\\xA3?\\d{1,}(?:\\,?\\d+)*(?:.\\d{1,2})?$/; Explanation:

  • ^ Matches the beginning of the string, or the beginning of a line.
  • xA3 Matches a "£" character (char code 163)
  • ? Quantifier for match between 0 and 1 of the preceding token.
  • \\d Matches any digit character (0-9).
  • {1,} Match 1 or more of the preceding token.
  • (?: Groups multiple tokens together without creating a capture group.
  • \\, Matches a "," character (char code 44).
  • {1,2} Match between 1 and 2 of the preceding token.
  • $ Matches the end of the string, or the end of a line if the multiline flag (

You could just make two passes:

/^£\d{1,3}(,\d{3})*(\.\d{2})?$/

to validate the format, and

/[1-9]/

to ensure that at least one digit is non-zero.

This is less efficient than doing it in one pass, of course (thanks, annakata, for the benchmark information), but for a first implementation, just "saying what you want" can significantly reduce developing time.

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