[翻译]  Java, how to replace a sequence of numbers in a string

[CHINESE]  Java,如何替换字符串中的数字序列


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.

我试图使用String.replace(a,b)来实现它,但没有成功。

3 个解决方案

#1


7  

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

由于您需要使用正则表达式,因此可以考虑使用replaceAll而不是replace。

#2


3  

You should use replaceAll. This method uses two arguments

你应该使用replaceAll。此方法使用两个参数

  1. regex for substrings we want to find
  2. 我们想要找到的子串的正则表达式
  3. replacement for what should be used to replace matched substring.
  4. 替换应该用于替换匹配的子串的内容。

In replacement part you can use groups matched by regex via $x where x is group index. For example

在替换部分中,您可以使用正则表达式通过$ x匹配的组,其中x是组索引。例如

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

将生成新的字符串,每两个小写字母替换 - 和第二个当前匹配的字母(注意第二个字母放在括号中,这意味着它在组1中,所以我可以在$ 1的替换部分中使用它)所以结果将是-b -df。

Now try to use this to solve your problem.

现在尝试使用它来解决您的问题。

#3


1  

You can use String.replaceAll with regular expressions:

您可以将String.replaceAll与正则表达式一起使用:

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

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号