Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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?

like image 833
Tony Avatar asked Jun 01 '26 08:06

Tony


1 Answers

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.
like image 194
anubhava Avatar answered Jun 02 '26 20:06

anubhava