(?=padrão)
A lookahead allows you to check if the group can be found by starting at the current position but not capturing or advancing the reading of the string being parsed. This way, you can check for two conditions in the same expression.
For example, to check if a string contains at least one "a"
character and a "b"
character:
^(?=.*a).*b
Regular expression
^[^ab]*+(?=(?:[^b]*b){2})(?:[^a]*a){2}[^a]*$
Online sample
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
, but does not advance the string reading.
-
(?:[^a]*a){2}[^a]*$
- House exactly two characters a
to the end of the string, but not 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 + " ✖️️");
}
}
Result
---aabb+++ ✔️
---bbaa+++ ✔️
---abab+++ ✔️
---baba+++ ✔️
---babba++ ✔️
---bbbbbaa ✔️
ababbb++++ ✔️
ccabcab+++ ✔️
----bcdbaa ✔️
-ababd++++ ✔️
bbbaabbbbb ✔️
bbbabbbbbb ✖️️
bbbaaabbbb ✖️️
baaaaaaaaa ✖️️
abbbbbbbbb ✖️️
ccacbcacbc ✔️
Online sample