Search code examples
regexscalareplaceall

How to lowercase the capture group only in scala


This code:

"""{"nAMe": "Deloise", "WINS": [["three of a kind", "5♣"]]}""".replaceAll("""(\"[^"]+\" *:)""", "|UPERCASETEST|$1|".toLowerCase())

Produces :

String = {|upercasetest|"nAMe":| "Deloise", |upercasetest|"WINS":| [["three of a kind", "5♣"]]}

While I was expecting :

String = {|upercasetest|"name":| "Deloise", |upercasetest|"wins":| [["three of a kind", "5♣"]]}

Any idea on why the capture group does not wish to lowercase and how to fix it?


Solution

  • You need to pass the match object to a lambda expression inside replaceAllIn where you may manipulate the contents, otherwise, inside replaceAll, the $1 does not get "expanded" to the actual Group 1 submatch value:

    val s = """{"nAMe": "Deloise", "WINS": [["three of a kind", "5♣"]]}"""
    val rx = """(\"[^"]+\" *:)""".r
    val replacedStr = rx replaceAllIn (s, m => s"|UPERCASETEST|${m.group(1)}|".toLowerCase())
    println(replacedStr)
    

    See Scala demo

    Output:

    {|upercasetest|"name":| "Deloise", |upercasetest|"wins":| [["three of a kind", "5♣"]]}