How to match any uppercase letter followed by the corresponding lower case letter?
java, regex
Solution
I admit to rising on the shoulders of giants (the other posters here), but this solution actually works for your use case:
final String[] strings = { "Aba", "ABa", "aba", "aBa", "Aaa", "Aab" };
final Pattern p = Pattern.compile("(\\p{Lu})(?=\\p{Ll}{2})(?i)(?!(\\1){2})");
for (String s : strings) System.out.println(s + ": " + p.matcher(s).find());
Now we have:
- a match for one upcase char at front;
- a lookahead assertion of two lowcase chars following;
- another lookahead that asserts these two chars are not both the same (ignoring case) as the first one.
Output:
Aba: true
ABa: false
aba: false
aBa: false
Aaa: false
Aab: true
Problem
I have a requirement that says a name must not start with 3 identical letters ignoring their case. A name starts with an upper case letter followed by lower case letters. Basically I could convert the whole name to upper case and then match with a regex like `(\p{Lu})\1{3,}.*`. But I was wondering if there exists a regex that matches the above requirements and does not need any preprocessing of the string to be matched. So what regex can I use to match strings like `Aa`, `Dd` or `Uu` without explicitly specifiying any possible combination? EDIT: I accepted Markos answer. I just needed to fix it to work with names of length 1 and two and anchor it at the beginning. So the actual regex for my use case is `^(\p{Lu})(\p{Ll}?$|(?=\p{Ll}{2})(?i)(?!(\1){2}))`. I also upvoted the answers of Evgeniy and sp00m for helping me to learn a lesson in regexes. Thanks for your efforts.