开发者

Regular expression to match dollar amounts

Could anybody provide me th开发者_如何学Ce regular expression for the following patterns?

$1234

$31234.3

$1234.56

$123456.78

$.99

My requirement is the digits before decimal should not exceed 6 and after the decimal point it should not exceed 2 digits. Please help me. Thanks in advance..


^\$(?=.*\d)\d{0,6}(\.\d{1,2})?$

(?=.*\d) makes sure that there is at least one digit in the string. Without that, the regex ^\$\d{0,6}(\.\d{1,2})?$ would match the string $.

Btw, the lookahead need not be this long; even a simple (?=.) would do, as the regex makes sure that the subsequent characters are indeed valid. Thus, it can be simplified to

^\$(?=.)\d{0,6}(\.\d{1,2})?$


^\$[0-9]{0,6}(\.[0-9]{1,2})?$


The pattern would be:

^\$\d{0,6}(\.\d{0,2})?$

This doesn't verify that there are any digits so "$." is a valid match and a valid result given the questioner's original requirements.

To explain:

^ means only match if there is nothing before the string I'm looking for, i.e. "USD$123.45" would fail in this example as the $ (matched with the \$) isn't immediately after the beginning of the string.

\$ matches the $ character, the use of the backslash () is called escaping and is used to allow you to match reserved characters (that mean something in the context of the regular expression) in this case $ which means match the end of the string, i.e. there are no characters after this point

\d will match any decimal character, i.e. 0-9

{n,m} will match from n to m instances of the preceding element, if n is 0 then it effectively means the match is optional.

\. will match the decimal point, it's escaped as . is a reserved character in the regular expression meaning match any character

(...) brings the regular expression contained within together as a group, there are other consequences but I'll leave that to you to explore. In this instance it's purely there for the benefit of the next character in the regular expression

? will match 0 or 1 of the preceding element (in this case the group which looks for a decimal point and up to 2 decimal characters, so we expect there to be no decimal point with trailing characters (0 occurrences) or a decimal point with up to 2 decimal characters (1 occurrence))

$ matches the end of the string, there can be no characters in the string after this point.


/^\$([0-9]{0-6})|^\$([0-9]{0-6})+\.([0-9]{0-2})$|\$\.([0-9]{0-2})$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜