0

Using these two regex expressions regPrefix and 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());
}

I am getting the correct output as:

1. the slithy toves
2. in the wabe.
3. were the borogoves,
4. mome raths outgrabe.

Is it possible to merge those two regex expressions into one, and get the same output? I tried something like:

String singleRegex = "(?m)^(\\S+)\\S+\\s+\\S+\\s+\\S+$";

but it didn't work for me.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79

1 Answers1

6

Use a single pattern with two capture groups:

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.

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360