Abdul Majid Bajwa
Abdul Majid Bajwa

Reputation: 159

Validating a numeric, 12-digit String containing a dash using regular expressions

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()

Upvotes: 1

Views: 659

Answers (2)

Jiri Tousek
Jiri Tousek

Reputation: 12450

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)

Upvotes: 2

Olivier Grégoire
Olivier Grégoire

Reputation: 35467

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*$");

Upvotes: 2

Related Questions