Search code examples
regexscalafunctional-programming

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


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).


Solution

  • 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