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.
"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
.
You should use replaceAll
. This method uses two arguments
regex
for substrings we want to find
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.
You can use String.replaceAll
with regular expressions:
"i ee44 a1 1222".replaceAll("(\\d+)", "($1)");