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
?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With