scala正则表达式组匹配和替换

时间:2012-12-05 16:53:00

标签: regex scala replace regex-group

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

3 个答案:

答案 0 :(得分:19)

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

"""hello { \" world \" } \n""".replaceAll("""([{}]|\\["n])""", "'$1'")
// => java.lang.String = hello '{' '\"' world '\"' '}' '\n'

答案 1 :(得分:12)

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

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

正则表达式中的括号允许您匹配它们之间的一个字符。 $1被正则表达式中括号之间的任何内容所取代。

答案 2 :(得分: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

希望这会有所帮助:)