Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

regex - Currency Regular Expression

I think I created a working regular expression for what I need. Just wondering if anyone can break it or see a shorter way to write it.

The regular expression should validate the following...

  • Dollar sign optional
  • Negative numbers signified with parenthesis, not a minus
  • If negative, dollar sign should be outside the parenthesis
  • Commas are optional
  • Max number is 999999.99
  • Min number is (999999.99)
  • Decimals do not have to be supplied, but if so, no more than two digits

So here are some examples of valid ones...

9
$9
$0.99
($999,999.99)
(999999)
($999999)
(999,999)
99,999.9

This is what I have come up with:

^$?(((d{1,6}(.d{1,2})?)|(d{1,3},d{3}(.d{1,2})?)|(((d{1,6}(.d{1,2})?)|(d{1,3},d{3}(.d{1,2})?)))))$

CORRECTION, my spec was wrong, if the dollar sign is used it must be INSIDE the parenthesis.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one shorter alternative (56 chars to your 114), which will work in almost all regex flavors:

^$?(?=(.*)|[^()]*$)(?d{1,3}(,?d{3})?(.dd?)?)?$

Example: http://www.rubular.com/r/qtYHEVzVK7

Explanation:

^                # start of string anchor
$?              # optional '$'
(?=              # only match if inner regex can match (lookahead)
   (.*)          # both '(' and ')' are present
   |               # OR
   [^()]*$         # niether '(' or ')' are present
)                # end of lookaheand
(?              # optional '('
d{1,3}          # match 1 to 3 digits
(,?d{3})?       # optionally match another 3 digits, preceeded by an optional ','
(.dd?)?       # optionally match '.' followed by 1 or 2 digits
)?              # optional ')'
$                # end of string anchor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...