import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?x) # Free spacing mode, to allow comment and better view\n\n"
+ "# Matching the first line `i5-2520M` (capture group 1)\n"
+ "([^ ]+\\s*)(?=CPU\\s*@)\n\n"
+ "# Matching the first line `2.50GHz` (capture group 2)\n"
+ "|(?<=CPU)(\\s*@\\s*\\d+.\\d+GHz)\n\n"
+ "# Matching the `first word` on the second line. (capture group 3)\n"
+ "# The `\\s*$` is used to not match empty lines.\n"
+ "|(^[^ ]+)(?!(?:.*CPU\\s*@)|\\s*$) \n\n"
+ "# Matching the second line `CPU T2400` (capture group 4)\n"
+ "|(?<=CPU)(\\s*[^ ]+\\s*)(?=@)\n\n"
+ "# Matching the second line `1.83GHz` (capture group 5)\n"
+ "|\\s*(?<=@)(\\s*\\d+.\\d+GHz)";
final String string = "Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz\n"
+ "Genuine Intel(R) CPU T2400 @ 1.83GHz\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