Extracting a substring using Matcher: java.lang.IllegalStateException: No match found

Viewed 81

I am trying to use regex to extract a substring from a given string. I am doing this in Scala:

val pattern = Pattern.compile("(Word)+")
val matcher = pattern.matcher("WordWordRestOfString")
matcher.group(1)

The desired output is "WordWord", however, I keep getting an IllegalStateException. I haven't really worked with Regex before, and cannot fully grasp how the matcher.group method works, but I have seen answers to questions suggesting the use of matcher.group(1).

2 Answers

First of all, the repeated capturing group only keeps the last captured value in the group memory buffer, so it is not surprising you onyl get Word as Group 1 value. See the Repeating a Capturing Group vs. Capturing a Repeated Group.

Second, you do not actually call the matcher .find or .matches method that actually trigger the regex search.

Third, you do not need to get Group 1 value here, you just need to get a full match:

val s = "WordWordRestOfStringWordWordWord"
val pattern = "(Word)+".r
// Single result:
val result = pattern.findFirstMatchIn(s).get
println(result) // => WordWord
// Multiple results:
val multiple_results = pattern.findAllMatchIn(s)
println(multiple_results.mkString(", ")) // => WordWord, WordWordWord

See the Scala demo

If I use group() instead of group(1), I do not face any issue getting the desired output in Java. I do not know Scala but I believe a Java code should work the same way is in Scala.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        var pattern = Pattern.compile("(Word)+");
        var matcher = pattern.matcher("WordWordRestOfString");
        if (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

Output:

WordWord

You can check this excellent tutorial on Regex, by Oracle.

Related