I want to replace all matches in a String with a dynamic number of characters; let's use [\d]+
as a simple example regex:
Desired results:
1984
->DDDD
1
->D
123456789
->DDDDDDDDD
a 123 b ->
a DDD b`
The common Java approach for replacing regex matches looks like this:
Pattern p = Pattern.compile("[\d]+");
String input = [...];
String replacement = ???;
String result = p.matcher(input).replaceAll(replacement);
My question is: do I have to extract the individual matches, measure their lengths, and then generate the replacement string based on that? Or does Java provide any more straightforward approach to that?
Update: I actually under-complicated the problem by giving rather simple examples. Here are some more that should be caught, taking more context into account:
<1984/>
(Regex:<[\d]+/>
) ->DDDDDDD
123.
->DDDD
, whereas:123
->123
(i.e. no match)
Note: I am not trying to parse HTML with a regex.