替换Scala中的一些子串

时间:2014-03-28 16:48:45

标签: regex scala

假设我需要替换字符串中的少数模式:

val rules = Map("abc" -> "123", "d" -> "4", "efg" -> "5"} // string to string
def replace(input:String, rules: Map[String, String] = {...}

replace("xyz", rules)       // returns xyz
replace("abc123", rules)    // returns 123123
replace("dddxyzefg", rules) // returns 444xyz5  

如何在Scala中实现replace?您如何概括rules : Map[Regex, String]的解决方案?

1 个答案:

答案 0 :(得分:4)

直接谈到一般情况可能更容易:

val replacements = Map("abc".r -> "123", "d".r -> "4", "efg".r -> "5")

val original = "I know my abc's AND my d's AND my efg's!"

val replaced = replacements.foldLeft(original) { (s, r) => r._1.replaceAllIn(s, r._2) }
replaced: String = I know my 123's AND my 4's AND my 5's!