yal*_*ris 17 regex replace scala 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'""")
Run Code Online (Sandbox Code Playgroud)
是否有更简单的方法来分组和替换所有这些{,},\",\n
?
Dao*_*Wen 20
您可以使用括号创建捕获组,并$1
在替换字符串中引用该捕获组:
"""hello { \" world \" } \n""".replaceAll("""([{}]|\\["n])""", "'$1'")
// => java.lang.String = hello '{' '\"' world '\"' '}' '\n'
Run Code Online (Sandbox Code Playgroud)
Dav*_*son 12
您可以像这样使用正则表达式组:
scala> """([abc])""".r.replaceAllIn("a b c d e", """'$1'""")
res12: String = 'a' 'b' 'c' d e
Run Code Online (Sandbox Code Playgroud)
正则表达式中的括号允许您匹配它们之间的一个字符.$1
由正则表达式中括号之间的任何内容替换.