I am trying to build a regular expression. Abbreviations are as follows:
B - Billion
M - Million
T - Thousand开发者_如何学JAVA
H - Hundred
Now, If I say 3M2T
it means 3 million 2 thousand
But I cannot say 3T2M
or I cannot say 3M2222T
BMTH should be in a sequence and should follow standard rule to create a number.
I went till this
([0-9]+[B]){1}+([0-9]+[M])?+([0-9]+[T])?+([0-9]+[H])?
But here B is compulsary.
Please help.
Try this:
^(?:\d+B)?(?:\d{1,3}M)?(?:\d{1,3}T)?(?:\dH)?$
You can test it here regexr.com?2thld
(?:)
is non capturing group, otherwise the captured part is stored in to a variable
\d
is equal to [0-9]
?
after a group or a character makes it optional
+
means one or more
{1,3}
says at least once at most three occurrences
[M]
is not needed when there is only 1 character then only M
is enough
([0-9]{1,3}B)?([0-9]{1,3}M)?([0-9]{1,3}T)?([0-9]H)?
Takes up to 3 digits for each B/M/T or 1 for H (in that order), each of the groups being optional. Add constraints suiting your needs…
Take note that [0-9]
is not necessarily equal to \d
, it depends on regional settings and stuff.
精彩评论