Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, how to replace a sequence of numbers in a string

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.

like image 272
Rakim Avatar asked Oct 24 '13 21:10

Rakim


People also ask

How do you replace a sequence in a string in Java?

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.

How do you replace all numbers in a string in Java?

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.

How do you replace multiple occurrences of a string in Java?

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.

How do you replace all digits in a 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.


2 Answers

"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.

like image 71
Terry Li Avatar answered Oct 31 '22 11:10

Terry Li


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.

like image 39
Pshemo Avatar answered Oct 31 '22 10:10

Pshemo