使用这两个正则表达式regPrefix
和regSuffix
,
final String POEM = "1. Twas brillig, and the slithy toves\n" +
"2. Did gyre and gimble in the wabe.\n" +
"3. All mimsy were the borogoves,\n" +
"4. And the mome raths outgrabe.\n\n";
String regPrefix = "(?m)^(\\S+)"; // for the first word in each line.
String regSuffix = "(?m)\\S+\\s+\\S+\\s+\\S+$"; // for the last 3 words in each line.
Matcher m1 = Pattern.compile(regPrefix).matcher(POEM);
Matcher m2 = Pattern.compile(regSuffix).matcher(POEM);
while (m1.find() && m2.find()) {
System.out.println(m1.group() + " " + m2.group());
}
我得到的正确输出为:
1. the slithy toves
2. in the wabe.
3. were the borogoves,
4. mome raths outgrabe.
是否可以将这两个正则表达式表达式合并为一个,并获得相同的输出?我尝试过类似的事情:
String singleRegex = "(?m)^(\\S+)\\S+\\s+\\S+\\s+\\S+$";
但这对我不起作用。
答案 0 :(得分:6)
使用具有两个捕获组的单个模式:
String regex = "(?m)^(\\S+).*?((?:\\s+\\S+){3})$";
Matcher m = Pattern.compile(regex).matcher(POEM);
while (m.find()) {
System.out.println(m.group(1) + m.group(2));
}
1. the slithy toves
2. in the wabe.
3. were the borogoves,
4. mome raths outgrabe.