import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?!(.*(?:[ -\\/:-@[-`\\{-~À-ÿ].*){4}))^[A-Za-z\\d -\\/:-@[-`\\{-~À-ÿ]{8,30}$";
final String string = "AABBCCDD\n"
+ "OK -- Match\n\n"
+ "aabbccdd\n"
+ "OK -- Match\n\n"
+ "11111111\n"
+ "OK -- Match\n\n"
+ "A1A1b2b2\n"
+ "OK -- Match\n\n"
+ "A@~D1dIo\n"
+ "OK -- Match\n\n"
+ "AAB BCC0\n"
+ "OK -- Match (1 special, it's okay)\n\n"
+ "AABBCC@@\n"
+ "OK -- Match (2 specials, it's okay)\n\n"
+ "AABB C \n"
+ "OK -- Match (3 specials, it's okay)\n\n"
+ "A@~` C:\n"
+ "OK -- Match (3 specials, it's okay)\n\n"
+ "AABB\n"
+ "OK -- Should't match and didn't match (Less than 8 symbols)\n\n"
+ "AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP\n"
+ "OK -- Should't match and didn't match (More than 30 symbols)\n\n"
+ "AA@@@@BB\n"
+ "ERROR ! -- Shouldn't match (4 specials, it's forbidden)\n\n"
+ "AAB B\n"
+ "ERROR ! -- Shouldn't match (4 specials, it's forbidden)\n\n"
+ "AABB@@@@\n"
+ "ERROR ! -- Shouldn't match (4 specials, it's forbidden)\n\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html