Search code examples
regexscalaregex-group

scala.MatchError when partitioning a string with an optional part into one or three parts


I am trying to pull out something like this:

params = {"path", "contentName"}

part of parametersStr below

@RequestMapping(value = "/breezeQuery", params = {"path", "contentName"}, method = RequestMethod.GET)

Why is this code giving me a scala.MatchError?:

val paramsPattern = """(.*)(?:params = \{.*})?(.*)""".r
val paramsPattern(left, paramsStr, right) = parametersStr

Also, the pattern like this may not occur in the string. So I also want to know if that is the case. Finally, I'm capturing everything to the left and right of the group so that I can concatenate them to remove the captured group from the string. It is optional, but I do want to capture it if it is present.


Solution

  • I believe you want to partition the string into 3 or 2 parts (depending on the optional params = \{.*}).

    You may use

    ^(.*?)(?:(params\s*=\s*\{.*?})(.*))?$
    

    See the regex demo. Details

    • ^ - start of string
    • (.*?) - Group 1 (left):
    • (?:(params\s*=\s*\{.*?})(.*))? - an optional non-capturing group, will be tried at least once:
      • (params\s*=\s*\{.*?}) - Group 2 (paramsStr):params word, = enclosed with 0+ whitespaces, {, any zero or more chars other than line break chars, as fewas possible and then }
      • (.*) - Group 3: any zero or more chars other than line break chars, as many as possible
    • $ - end of string

    See the Scala demo:

    val parametersStr = """@RequestMapping(value = "/breezeQuery", params = {"path", "contentName"}, method = RequestMethod.GET)"""
    val paramsPattern = """^(.*?)(?:(params\s*=\s*\{.*?})(.*))?$""".r
    val paramsPattern(left, paramsStr, right) = parametersStr
    println(s"Left: $left\nParam String: $paramsStr\nRight: $right")
    

    Output:

    Left: @RequestMapping(value = "/breezeQuery", 
    Param String: params = {"path", "contentName"}
    Right: , method = RequestMethod.GET)