I want to make two regex replacements on one string, i.e. in Java terms
myString.replaceAll(pattern1, replacement1).replaceAll(pattern2, replacement2);
However, suppose that myString may be very long, so it would be desirable to avoid doing two passes over it. Can this be done in single pass?
String pattern = ...;
String replacement = ...;
myString.replaceAll(pattern, replacement);
The obvious candidate for pattern is pattern1 + "|" + pattern2, but then I can’t see how to write replacement.
To simplify, let’s assume that matches of pattern1 and pattern2 can’t intersect, and that replacement1 doesn’t introduce any new matches of pattern2.
The easiest way to do this is to maintain a hash that maps strings to their replacements. Compose a match that matches any of the keys, and pass the matched key to the replacement portion. Have the replacement portion than pull in the value.
In Perl, that would merely be:
The equivalent Java solution would — like everything — be significantly longer, but the same approach would work.
Ordering issue do arise if one string is a starting substring of another.