import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3,4}$)|(^#[0-9A-Fa-f]{8}$)";
final String string = "// good case\n"
+ "#000\n"
+ "#123\n"
+ "#999\n"
+ "#AAA\n"
+ "#aaa\n"
+ "#abc\n"
+ "#FFF\n"
+ "#0000\n"
+ "#9999\n"
+ "#AAAA\n"
+ "#aaaa\n"
+ "#abcd\n"
+ "#FFFF\n"
+ "#ffff\n"
+ "#000000\n"
+ "#456789\n"
+ "#999999\n"
+ "#AAAAAA\n"
+ "#aaaaaa\n"
+ "#abcdef\n"
+ "#FFFFFF\n"
+ "#ffffff\n"
+ "#00000000\n"
+ "#12345678\n"
+ "#99999999\n"
+ "#AAAAAAAA\n"
+ "#aaaaaaaa\n"
+ "#abcdefcc\n"
+ "#FFFFFFFF\n"
+ "#ffffffff\n"
+ "#00123456\n\n\n"
+ "//bad case\n"
+ "##\n"
+ "#0\n"
+ "#1\n"
+ "#F\n"
+ "#f\n"
+ "#12\n"
+ "#AB\n"
+ "#ae\n"
+ "#aaaaa\n"
+ "#fffff\n"
+ "#aaaah\n"
+ "#aaaaaaa\n"
+ "#0000000\n"
+ "#ffffhij\n"
+ "#h000000\n"
+ "#aaaaaaai\n"
+ "#000k0123\n"
+ "#asdfasfa\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