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

2020-04-05 07:22发布

问题:

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:

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



回答2:

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.



回答3:

You can use String.replaceAll with regular expressions:

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