virtualpathum virtualpathum - 23 days ago 8
Java Question

Regex validation for pattern 20+99

Hi my requirement is like this

Required text format
20+99


  1. maximum allowed number should be 20 for left side from the + mark

  2. right side maximum number should be 99

  3. should allow only two characters each side



Other allowed formats


  1. 1+1

  2. 0+0

  3. 01+01



We tried followings

[0-9]{1,2}([+])[0-9]{1,2}

(^[01][0-9]|20)([+])[0-9]{1,2}

Problem with first approach is cannot limit left side to 20 and it allows more than 2 characters each side.

Problem with the second approach is it does not allow 1+1 or 0+0.
Appreciate some support to modify the regex to cater our requirement.

Answer

Adapted from your second attempt :

^(?:[01]?[0-9]|20)\+[0-9]{1,2}$