(?=padrão)
A Lookahead allows checking whether the group can be found by starting at the position it is in, but without capturing or advancing the reading of the string being analyzed. This way you can check if there are two conditions in the same expression.
For example, to check whether a string contains at least one character "a"
and a character "b"
:
^(?=.*a).*b
Regular expression
^[^ab]*+(?=(?:[^b]*b){2})(?:[^a]*a){2}[^a]*$
Online example
Meaning
^[^ab]*+
- Optional characters that are not a
nor b
at the beginning of the string.
(?=(?:[^b]*b){2})
- Lookahead to check for two b
, no further progress on string reading.
(?:[^a]*a){2}[^a]*$
- Matches exactly two characters a
until the end of the string, but no more than two.
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^[^ab]*+(?=(?:[^b]*b){2})(?:[^a]*a){2}[^a]*$";
String[] exemplos = new String[] {
"---aabb+++", "---bbaa+++", "---abab+++", "---baba+++",
"---babba++", "---bbbbbaa", "ababbb++++", "ccabcab+++",
"----bcdbaa", "-ababd++++", "bbbaabbbbb", "bbbabbbbbb",
"bbbaaabbbb", "baaaaaaaaa", "abbbbbbbbb", "ccacbcacbc"
};
final Pattern pattern = Pattern.compile(regex);
for (String palavra : exemplos) {
Matcher matcher = pattern.matcher(palavra);
if (matcher.find()) {
System.out.println(palavra + " ✔️");
} else {
System.out.println(palavra + " ✖️️");
}
}
Upshot
---aabb+++ ✔️
---bbaa+++ ✔️
---abab+++ ✔️
---baba+++ ✔️
---babba++ ✔️
---bbbbbaa ✔️
ababbb++++ ✔️
ccabcab+++ ✔️
----bcdbaa ✔️
-ababd++++ ✔️
bbbaabbbbb ✔️
bbbabbbbbb ✖️️
bbbaaabbbb ✖️️
baaaaaaaaa ✖️️
abbbbbbbbb ✖️️
ccacbcacbc ✔️
Online example
.*a{2}b{2,}.*
see if it fits.– user28595
It did not work because it did not validate the string "Babba", and in this exercise, this string would be valid
– Raphael Prado de Oliveira