1

I need to validate that a given String contains up to 12 digits and exactly one dash.

Initial RegEx: ^[0-9]*-?[0-9]*$

Modified RegEx: ^([0-9]*-?[0-9]*){1,12}$

Example (should be valid): 12356978-9

The problem is that the first RegEx doesn't validate the length, and the second one doesn't work.

Note: Everything must be done in regex, not checking length using string.length()

2 Answers2

2

The ugly way:

^([0-9]-[0-9]{1,11}|[0-9]{2}-[0-9]{1,10}|[0-9]{3}-[0-9]{1,9}| ...)$

Using lookahead, combining two conditions:

^(?=\\d*-\\d*$)(?=.{1,13}$).*$

(Inspired by this Alan Moore's answer)

Community
  • 1
  • 1
Jiri Tousek
  • 11,964
  • 5
  • 27
  • 41
2

If you can use extra conditions outside of the regex:

String s = ... ;
return s.length()<=13 && s.matches("^\\d+-\\d+$");

If a dash can start or end the string, you can use the following:

String s = ... ;
return s.length()<=13 && s.matches("^\\d*-\\d*$");
Olivier Grégoire
  • 31,286
  • 22
  • 93
  • 132