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:

3
  • Could you please post the code for the num:[0-9]+ case? Commented Dec 8, 2009 at 12:01
  • What should happen to numbers within words - 123foo, foo123 or foo123foo? Then there's signed numbers (-123), formatted numbers (1,234) and decimals (1,234.567). Commented Dec 8, 2009 at 12:04
  • @Greg: Just edit the regex, no? Commented Dec 8, 2009 at 12:12

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

Comments

4
"foo bar 567 baz".replaceAll("(\\d+)", "num:$1");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.