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 in brackets. So the input is:

"i ee44 a1 1222" 

Must have an output:

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

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

+6
source share
3 answers
 "i ee44 a1 1222".replaceAll("\\d+", "($0)"); 

Try this and see if it works.

Since you need to work with regular expressions, you can use replaceAll instead of replace .

+7
source

You must use replaceAll . This method uses two arguments

  • regex for the substrings we want to find
  • replacement for what should be used to replace substring substring.

In the replacement section, you can use the groups matched by the regular expression through $x , where x is the group index. for instance

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

will create a new line with the replacement of each two lowercase letters with - and the second currently matching letter (note that the second letter is placed in brackets, so this means that it is in group 1, so I can use it in the replacement part with using $1 ), so the result would be -b -df .

Now try using this to solve your problem.

+3
source

You can use String.replaceAll with regular expressions:

 "i ee44 a1 1222".replaceAll("(\\d+)", "($1)"); 
+1
source

Source: https://habr.com/ru/post/956681/


All Articles