0

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:

  1. 1984 -> DDDD
  2. 1 -> D
  3. 123456789 -> DDDDDDDDD
  4. 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:

  1. <1984/> (Regex: <[\d]+/>) -> DDDDDDD
  2. 123. -> DDDD, whereas: 123 -> 123 (i.e. no match)

Note: I am not trying to parse HTML with a regex.

Carsten
  • 1,912
  • 1
  • 28
  • 55
  • 1
    You're over-complicating this. Just use `\d` with replacement as `D` as shown [here](https://regex101.com/r/oXdZDK/1) – ctwheels Feb 23 '18 at 16:41
  • 2
    If you just want to replace numbers with `D` why does the match length matter at all? Just do `input.replaceAll("\\d", "D");` – BackSlash Feb 23 '18 at 16:41

1 Answers1

1

You're really overthinking/overcomplicating this. Just use \d with replacement as D as seen here. There's no need to get the length of the string or do any additional processing; just a straight up replaceAll()

See code in use here

final String[] a = {"1984","1","123456789","a 123 b"};
for (String s: a) {
    System.out.println(s.replaceAll("\\d","D"));
}
ctwheels
  • 21,901
  • 9
  • 42
  • 77