scala regex group matching and replace

yalkris picture yalkris · Dec 5, 2012 · Viewed 24k times · Source
val REGEX_OPEN_CURLY_BRACE = """\{""".r
val REGEX_CLOSED_CURLY_BRACE = """\}""".r
val REGEX_INLINE_DOUBLE_QUOTES = """\\\"""".r
val REGEX_NEW_LINE = """\\\n""".r

// Replacing { with '{' and } with '}'
str = REGEX_OPEN_CURLY_BRACE.replaceAllIn(str, """'{'""")
str = REGEX_CLOSED_CURLY_BRACE.replaceAllIn(str, """'}'""")
// Escape \" with '\"' and \n with '\n'
str = REGEX_INLINE_DOUBLE_QUOTES.replaceAllIn(str, """'\"'""")
str = REGEX_NEW_LINE.replaceAllIn(str, """'\n'""")

Is there a simpler way to group and replace all of these {,},\",\n?

Answer

DaoWen picture DaoWen · Dec 5, 2012

You can use parenthesis to create a capture group, and $1 to refer to that capture group in the replacing string:

"""hello { \" world \" } \n""".replaceAll("""([{}]|\\["n])""", "'$1'")
// => java.lang.String = hello '{' '\"' world '\"' '}' '\n'