Java:正则表达式替换 [英] Java: Regex replacing
本文介绍了Java:正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:
foo bar 567 baz
现在我想在每个数字之前添加String num:
。
所以结果必须是:
Now I want to add before each number the String num:
.
So the result has to be:
foo bar num:567 baz
这也必须有效:
foo 73761 barbazboom!! 87
result:
foo num:73761 barbazboom!! num:87
搜索号的正则表达式为: [0-9 ] +
但我想用 num:
+ [匹配的子串]
The regex to search number is this: [0-9]+
But I want to replace the matching substring with num:
+ [the matching substring]
我现在用数字写了一个例子,但另一个例子可以是:在每个电子邮件地址之前添加找到的电子邮件:
I now wrote an example with numbers, but an other example can be: add before each e-mail-address Email found:
推荐答案
利用分组。您可以使用括号(
和)
来定义组,并通过 $ n
其中 n
是组索引。
Make use of grouping. You can use the parentheses (
and )
to define groups and identify the group in the result by $n
where n
is the group index.
String string = "foo bar 567 baz";
String replaced = string.replaceAll("(\\d+)", "num:$1");
这篇关于Java:正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文