1

I'm having trouble putting together a regular expression for a string that contains a number between 0 and 99999, followed by a plus sign, followed by one or two digits, optionally followed by a decimal and a single digit. For instance:

99999+99.9

This would also be valid:

0+00

This would also be valid:

0+02.5

This would also be valid:

0+2.5

I found this topic: How can I check for a plus sign using regular expressions?

And this one: Regular Expression for decimal numbers

But am unable to put the 2 together and fulfill the other requirements listed above.

Any help you can provide is much appreciated!

Community
  • 1
  • 1
Chad Ernst
  • 107
  • 1
  • 10

3 Answers3

4

This should work:

\d{1,5}\+\d{1,2}(?:\.\d)?
  1. \d{1,5} captures anything between 0 and 99999 but also allows zero padding, e.g. 00000 or 00123 (it'll be a little more complicated if you don't want zero padding).

  2. \+ matches a plus sign.

  3. \d{1,2} matches one or two digits.

  4. (?:\.\d) matches a period followed by a single digit. The (?:) bit indicates a non-capture group.

  5. The ? at the end makes the non-capture group optional.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • The only problem with this is it allows non-numeric characters as well. (i.e. 99b99+99.9 should not be valid because of "b"). – Chad Ernst Sep 16 '11 at 15:20
0

Here it is

"^[0-9]*([0-9]{0,5}\+[0-9]{1,2}(\.[0-9])?)[0-9]*$"

EDIT: as per you comment, I have modified the expression.

Jayy
  • 2,368
  • 4
  • 24
  • 35
  • I should have been more clear in my question. Non-numeric characters should not be valid. – Chad Ernst Sep 16 '11 at 15:21
  • The solution you proposed prevents non-numeric characters - however, it allows more than 5 characters to the left of the plus sign. Any way to enforce a max of 5 characters to the left of the plus sign? – Chad Ernst Sep 16 '11 at 17:43
  • Actually, it doesn't enforce 5 characters to the left of plus sign, 2 characters to the right of plus sign, or 2 characters to the right of decimal (if decimal was supplied). – Chad Ernst Sep 16 '11 at 18:14
0

You need to escape the plus and the . -- like so

\d{1,5}\+\d{1,2}\.?\d

Hth!

Sunder
  • 1,445
  • 2
  • 12
  • 22