简体   繁体   中英

Javascript Regular expression for currency amount with spaces

I have this regular expression

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

It matches this very well $55.5, but in few of my test data I have some values like $ 55.5 (I mean, it has a space after $ sign).

The answers on this link are not working for me. Currency / Percent Regular Expression

So, how can I change it to accept the spaces as well?

Try following RegEx :

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

Let me know if it worked!

Demo Here

TLDR:

/^[',",\+,<,>,\(,\*,\-,%]?([£,$,€]?\s*\d+([\,,\.]\d+)?[£,$,€]?\s*[\-,\/,\,,\.,\+]?[\/]?\s*)+[',",\+,   <,>,\),\*,\-,%]?$/

The science bit

Ok, I'm guessing that you didn't construct the original regular expression, so here are the pieces of it, with the addition marked:

^ # match from the beginning of the string
[',",\+,<,>,\(,\*,\-,%]?    # optionally one of these symbols
(                           # start a group
   [£,$,€]?                   # optionally one of these symbols
   \s*                        # <--- NEW ADDITION: optionally one or more whitespace
   \d+                        # then one or more decimal digits
   (                          # start group 
      [\,,\.]                   # comma or a dot
      \d+                       # then one or more decimal digits
   )?                         # group optional (comma/dot and digits or neither)
   [£,$,€]?                   # optionally one of these symbols
   \s*                        # optionally whitespace
   [\-,\/,\,,\.,\+]?          # optionally one of these symbols
   [\/]?                      # optionally a /
   \s*                        # optionally whitespace
)+                          # this whole group one or more times
[',",\+,   <,>,\),\*,\-,%]? # optionally one of these symbols
$ # match to the end of the string

Much of this is poking about matching stuff around the currency amount, so you could reduce that.

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