1

Suppose I need to replace few patterns in a string :

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  

How would you implement replace in Scala ? How would you generalize the solution for rules : Map[Regex, String] ?

1 Answer 1

5

It's probably easier just to go straight to the general case:

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!
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, thanks. Looks like looping over all replacements and call replaceAllfor each of them. Is it optimal performance/complexity-wise?
I don't think there's a straightforward alternative. If all the replacement targets had the same replacement string, you could combine the target patterns with the | regex operator and do a single replaceAllIn. Otherwise, there's nothing simple I can think of. But unless you have gobs of replacemens in your Map or the multi-replace will happen in an "inner loop," the performance probably won't be a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.