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.
Java String replace() The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.
you can use Java - String replaceAll() Method. This method replaces each substring of this string that matches the given regular expression with the given replacement.
You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.
To replace all numbers in a string, call the replace() method, passing it a regular expression that globally matches all numbers as the first parameter and the replacement string as the second. The replace method will return a new string with all matches replaced by the provided replacement.
"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 findreplacement
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With