3

I have this String:

foo bar 567 baz

Now I want to add before each number the String num:.
So the result has to be:

foo bar num:567 baz

Also this has to work:

foo 73761 barbazboom!! 87
result:
foo num:73761 barbazboom!! num:87

The regex to search number is this: [0-9]+
But I want to replace the matching substring with num: + [the matching substring]

I now wrote an example with numbers, but an other example can be: add before each e-mail-address Email found:

Cœur
  • 37,241
  • 25
  • 195
  • 267
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287

2 Answers2

8

Make use of grouping. You can use the parentheses ( and ) to define groups and identify the group in the result by $n where n is the group index.

String string = "foo bar 567 baz";
String replaced = string.replaceAll("(\\d+)", "num:$1");
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
4
"foo bar 567 baz".replaceAll("(\\d+)", "num:$1");
dfa
  • 114,442
  • 31
  • 189
  • 228