Reputation: 173
I am trying to create a regular expression with Unique digits separated with comma with max 5 digit and numbers are allowed from 1-10. for example
1,2,3,4,5 - valid
1,2,2,4,5 - Invalid (Because it's allowing to define duplicate digits)
but I want regular expression in which we can enter only unique number. I am mentioning below my regex which allow digits with comma separated and allow 5 digits between 1-10.
^([1-9]|10)(?:,([1-9]|10)){0,4}$
Please help how to define this regex which allow only unique digits
Upvotes: 2
Views: 503
Reputation: 626738
You may use
^(?!.*\b(\d+)\b.*\b\1\b)(?:[1-9]|10)(?:,(?:[1-9]|10)){0,4}$
See an online regex demo.
The (?!.*\b(\d+)\b.*\b\1\b)
negative lookahead fails any match if there are repeated identical digit chunks as whole words (enclosed with word boundary positions).
See the Java demo:
List<String> strs = Arrays.asList("1,2,3,4,5", "1,2,2,4,5");
String rx = "(?!.*\\b(\\d+)\\b.*\\b\\1\\b)(?:[1-9]|10)(?:,(?:[1-9]|10)){0,4}";
for (String str : strs)
System.out.println(str + ": " + str.matches(rx));
Output:
1,2,3,4,5: true
1,2,2,4,5: false
Note that ^
and $
at the start and end of the pattern are omitted in Java code since .matches
requires a full string match.
Upvotes: 2