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'
Question
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
?
Solution
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'
OTHER TIPS
You can use regex groups like so:
scala> """([abc])""".r.replaceAllIn("a b c d e", """'$1'""")
res12: String = 'a' 'b' 'c' d e
The brackets in the regex allows you to match one of the characters between them. $1
is replaced by whatever is found between the parentheses in the regular expressions.
Consider this is your string :
var actualString = "Hi { { { string in curly brace } } } now quoted string : \" this \" now next line \\\n second line text"
Solution :
var replacedString = Seq("\\{" -> "'{'", "\\}" -> "'}'", "\"" -> "'\"'", "\\\n" -> "'\\\n'").foldLeft(actualString) { _.replaceAll _ tupled (_) }
scala> var actualString = "Hi { { { string in curly brace } } } now quoted string : \" this \" now next line \\\n second line text"
actualString: String =
Hi { { { string in curly brace } } } now quoted string : " this " now next line \
second line text
scala> var replacedString = Seq("\\{" -> "'{'", "\\}" -> "'}'", "\"" -> "'\"'", "\\\n" -> "'\\\n'").foldLeft(actualString) { _.replaceAll _ tupled (_) }
replacedString: String =
Hi '{' '{' '{' string in curly brace '}' '}' '}' now quoted string : '"' this '"' now next line \'
' second line text
Hope this will help :)