2012-12-05 36 views
9
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'""") 

是否有更簡單的方法來組合和替換所有這些{,},\",\nscala正則表達式組匹配和替換

回答

12

您可以使用括號來創建一個捕獲組,並$1指代捕獲組替換字符串:

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

我仍然不確定你想用引號做什麼,但我認爲這就是你現在要做的...... – DaoWen

+0

並且用較少的反斜槓:「」「{」\ n}「」「」。 replaceAll(「」「([」{} \\ n])「」「,」'$ 1'「) – yakshaver

+0

@yakshaver - 您的示例將分別替換'n'和'\',例如'「no」'=>'「'n'o」'。至於引號前面的反斜線,這就是爲什麼我說我不確定他想用引號做什麼。我想他可能實際上是在尋找''''而不是''''自己。 – DaoWen

10

您可以使用正則表達式組,像這樣:

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

在正則表達式中括號讓您根據它們之間的人物之一。 $1被替換爲正則表達式中括號之間的內容。

+0

由於他的序列是多字符(有時),我認爲交替會更好。 – FrankieTheKneeMan

+1

'$ 0'實際上綁定到整個匹配字符串。 「$ 1」被綁定到第一個匹配組。在這種情況下,他們碰巧是相同的,儘管第一輪比賽組包含了整個模式。 – DaoWen

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 

希望這會有所幫助:)

+1

有了這個舊的問題,如果你指出你的答案提供了其他答案沒有的答案,它會有所幫助。 – jwvh

+0

當你在這裏。請修正格式:) –