Chad Ernst
Chad Ernst

Reputation: 117

Regular Expression that includes plus sign and decimal

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!

Upvotes: 2

Views: 8772

Answers (3)

Jayy
Jayy

Reputation: 2436

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.

Upvotes: 0

Sunder
Sunder

Reputation: 1513

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

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

Hth!

Upvotes: 0

BoltClock
BoltClock

Reputation: 723538

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.

Upvotes: 4

Related Questions