23
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'""")

有没有更简单的方法来分组和替换所有这些{,},\",\n

4

3 回答 3

28

您可以使用括号创建一个捕获组,并$1在替换字符串中引用该捕获组:

"""hello { \" world \" } \n""".replaceAll("""([{}]|\\["n])""", "'$1'")
// => java.lang.String = hello '{' '\"' world '\"' '}' '\n'
于 2012-12-05T17:46:13.343 回答
12

您可以像这样使用正则表达式组:

scala> """([abc])""".r.replaceAllIn("a b c d e", """'$1'""")
res12: String = 'a' 'b' 'c' d e

正则表达式中的括号允许您匹配它们之间的字符之一。$1替换为正则表达式中括号之间的任何内容。

于 2012-12-05T17:43:36.193 回答
0

考虑这是你的字符串:

var actualString = "Hi {  {  { string in curly brace }  }   } now quoted string :  \" this \" now next line \\\n second line text"

解决方案 :

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

希望这会有所帮助:)

于 2017-07-31T06:45:05.667 回答