Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala regex group matching and replace

Tags:

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?

like image 902
yalkris Avatar asked Dec 05 '12 16:12

yalkris


1 Answers

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' 
like image 63
DaoWen Avatar answered Sep 23 '22 11:09

DaoWen