Tony Tony - 18 days ago 4
Java Question

Make Java regex '[abc]+' match once per letter

String[] words = {"a","ab","ac","abc","aac","aa"};
for(String str:words) {
if(str.matches("[abc]+")) {
System.out.println(str);
}
}


This code print out


a,ab,ac,abc,aac,aa


This is almost what I want except I do not want a letter be matched twice. I want to change the regex
[abc]+
so that the match will only happen once. The
aac
and
aa
should not printed because
aa
is matched twice.
Can I do this?

Answer

Using negative lookahead you can use this regex:

^(?:([abc])(?!.*\1))+$

RegEx Demo

If you want to allow any character not just [abc] then use:

^(?:(.)(?!.*\1))+$
  • (.) matches and groups any character
  • (?!.*\1) is negative lookahead that asserts for each character captured, that the same character does not exist ahead of the current position.
  • (?:...)+ groups matching character and lookahead in a non-capturing group which is repeated 1 or more times to match whole string.