Tony Tony - 1 year ago 54
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]+")) {

This code print out


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

Answer Source

Using negative lookahead you can use this regex:


RegEx Demo

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

  • (.) 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download