import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\b(?:(?=.{0,3}?\\d)[A-Za-z\\d]{4}\\s??){3}\\b";
final String string = "?K9X6 6GM6 LM11 // not recognized - but it should be\n"
+ "!K9X6 6GM6 LM11 // not recognized - but it should be\n"
+ "K0X6 0GM7 LM12! // not recognized - but it should be\n"
+ "K1X6 1GM8 LM13@ // not recognized - but it should be\n"
+ "K2X6 2GM9 LM14? // not recognized - but it should be\n"
+ "K3X6 3GM0 LM15# // not recognized - but it should be\n"
+ "K4X6 4GM1 LM16* // not recognized - but it should be\n"
+ "K5X65GM2LM17\n"
+ "bla bla bla\n"
+ "this shouldn't be visible\n"
+ "spod also shouldn't be visible\n"
+ "but line below should be!!\n"
+ "K9X66GM6LM11! (see that \"!\" at the end? Help me with this)\n\n"
+ "K5X65GM2LM17234324122323 //wrong, text is too long\n"
+ "A9D24 A12E A59E3 //wrong, text block counts 5 characters!\n";
final Pattern pattern = Pattern.compile(regex);
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