24
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?

ekad
  • 14,436
  • 26
  • 44
  • 46
yalkris
  • 2,596
  • 5
  • 31
  • 51

3 Answers3

31

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'
DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • I'm still not sure exactly what you wanted to do with the quotes, but I think this is what you were going for now... – DaoWen Dec 05 '12 at 17:59
  • And with fewer back slashes: """{ " \n }""".replaceAll("""(["{}\\n])""", "'$1'") – yakshaver Dec 05 '12 at 18:09
  • @yakshaver - Your example replaces `n` and `\ ` separately, e.g. `"no"` => `"'n'o"`. As for the backslash in front of the quotation mark, that's why I said I wasn't sure what he wanted to do with the quotes. I think he might actually be looking for `\"` rather than just `"` on its own. – DaoWen Dec 06 '12 at 07:06
  • 1
    You're right. How about this: "{ \" \n }".replaceAll("""(["{}\n])""", "'$1'") – yakshaver Dec 06 '12 at 16:26
  • @yakshaver - Now it replaces an actual newline instead of the sequence of characters _backslash n_. – DaoWen Dec 07 '12 at 03:03
16

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.

David Pärsson
  • 6,038
  • 2
  • 37
  • 52
  • Since his sequences are multicharacter(sometimes), I think alternation would work better. – FrankieTheKneeMan Dec 05 '12 at 17:44
  • 2
    `$0` is actually bound to the entire matching string. `$1` is bound to the first match group. In this case they happen to be the same though since the first match group encompasses the whole pattern. – DaoWen Dec 05 '12 at 17:48
0

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 :)

0x6C38
  • 6,796
  • 4
  • 35
  • 47
Sam
  • 139
  • 1
  • 10
  • 2
    With a question this old it helps if you point out what your answer provides that the other answers don't. – jwvh Jul 31 '17 at 06:58