Tricky Regex - Replace only the first occurrence and not the next occurence

Viewed 76

Need to match and replace all first occurrences of plus alone with %2b

Example

Input        Output
++123++      %2b%2b123++
+++++12      %2b%2b%2b%2b%2b12
12           12
123+         123+
+1           %2b1
+2           %2b2

How to do this via regex? It is possible to do via character matching in java but wanted to see whether it is possible via regex pattern?

System.out.println("+++123".replaceFirst("\\+", "%2b")); ==> Just removes the first character alone

1 Answers

This is a great use case for \G - which matches the beginning of the string or at the position the previous match ended:

System.out.println("+++123++".replaceAll("\\G\\+", "%2b"));

Here's another option that is more easily expandable:

import java.util.regex.Pattern;
import java.net.URLEncoder;
...

String result = Pattern.compile("^\\++").matcher("+++123++")
                     .replaceAll(mr -> URLEncoder.encode(mr.group()).toLowerCase());

Here we're using an overload of relpaceAll that takes a callback and can dynamically calculate the result string, and URLEncoder to get the right number of pluses.

Related