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?
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With