7

I am trying to replace any sequence of numbers in a string with the number itself within brackets. So the input:

"i ee44 a1 1222"  

Should have as an output:

"i ee(44) a(1) (1222)"

I am trying to implement it using String.replace(a,b) but with no success.

1
  • 1
    Can you show what you tried? Commented Oct 24, 2013 at 21:30

3 Answers 3

9
"i ee44 a1 1222".replaceAll("\\d+", "($0)");

Try this and see if it works.

Since you need to work with regular expressions, you may consider using replaceAll instead of replace.

Sign up to request clarification or add additional context in comments.

Comments

3

You should use replaceAll. This method uses two arguments

  1. regex for substrings we want to find
  2. replacement for what should be used to replace matched substring.

In replacement part you can use groups matched by regex via $x where x is group index. For example

"ab cdef".replaceAll("[a-z]([a-z])","-$1") 

will produce new string with replaced every two lower case letters with - and second currently matched letter (notice that second letter is placed parenthesis so it means that it is in group 1 so I can use it in replacement part with $1) so result will be -b -d-f.

Now try to use this to solve your problem.

Comments

1

You can use String.replaceAll with regular expressions:

"i ee44 a1 1222".replaceAll("(\\d+)", "($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.