How to Replace the String Between Two Characters in Java
Replacing specific characters in a string is quite easy in Java (using replace()
), but how can we replace an entire substring between two characters?
Suppose we have a string that is meant to represent a URL path.
String url = "/path/{id}/resource";
Let’s say we want to replace the string between the opening and closing curly braces {}
with an asterisk *
.
String updatedUrl = "/path/*/resource";
Using replaceAll()
We can do this using replaceAll()
.
The first parameter takes in a regular expression while the second takes in a string with the replacement value.
String start = "\\{";
String end = "\\}";
String updatedUrl = url.replaceAll(start + ".*" + end, "*");
Our start
and end
symbols need to be escaped if they are special characters used in regular expressions.
In Java, these characters will need to be escaped: \.[]{}()<>*+-=!?^$|
.
In order to escape a special character, we can add the a single backslash \
, or the escape character, before the special character.
However, we also need to escape that backslash with the escape character (hint: another backslash), since it too is a special character.
This is why we will often see double backslashes \\
in regular expressions.
This string \\{.*\\}
translates to the sequence \{.*\}
, which literally matches our url
against {.*}
.
Greediness
While this is a great start to using regular expressions in our replaceAll()
method, we’ll have to deal with the greediness of our matching.
This relates to the .*
portion of the regular expression.
Greedy | Reluctant | Possessive | Meaning |
---|---|---|---|
X? | X?? | X?+ | X, once or not at all |
X* | X*? | X*+ | X, zero or more times |
X+ | X+? | X++ | X, one or more times |
X{n} | X{n}? | X{n}+ | X, exactly n times |
X{n,} | X{n,}? | X{n,}+ | X, at least n times |
X{n,m} | X{n,m}? | X{n,m}+ | X, at least n but not more than m times |
Based on our use case, we can vary our greedy quantifiers to match as little or as much as we need.