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
  • 12,211
  • 5
  • 29
  • 43
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
  • 33,839
  • 23
  • 96
  • 137