Say I have a file, that contains some text. There are substrings like “substr1”, “substr2”, “substr3” etc. in it. I need to replace all of those substrings with some other text, like “repl1”, “repl2”, “repl3”. In Python, I would create a dictionary like this:
{
"substr1": "repl1",
"substr2": "repl2",
"substr3": "repl3"
}
and create the pattern joining the keys with ‘|’, then replace with re.sub function.
Is there a similar simple way to do this in Java?
This is how your Python-suggestion translates to Java:
This approach does a simultanious (i.e. “at once”) replacement. I.e., if you happened to have
then this approach would give
"a b" -> "b c"as opposed to the answers suggesting you should chain several calls toreplaceorreplaceAllwhich would give"c c".(If you generalize this approach to create the regexp programatically, make sure you
Pattern.quoteeach individual search word andMatcher.quoteReplacementeach replacement word.)