[英]Java: Regex replacing
I have this String: 我有这个字符串:
foo bar 567 baz
Now I want to add before each number the String num:
. 现在我想在每个数字之前添加String num:
.
So the result has to be: 所以结果必须是:
foo bar num:567 baz
Also this has to work: 这也必须工作:
foo 73761 barbazboom!! 87
result:
foo num:73761 barbazboom!! num:87
The regex to search number is this: [0-9]+
搜索号的正则表达式为: [0-9]+
But I want to replace the matching substring with num:
+ [the matching substring] 但我想用num:
+ [匹配子字符串]替换匹配的子字符串
I now wrote an example with numbers, but an other example can be: add before each e-mail-address Email found:
我现在用数字写了一个例子,但另一个例子可以是:在每个电子邮件地址之前添加Email found:
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. 您可以使用括号(
和)
来定义组,并通过$n
在结果中标识组,其中n
是组索引。
String string = "foo bar 567 baz";
String replaced = string.replaceAll("(\\d+)", "num:$1");
"foo bar 567 baz".replaceAll("(\\d+)", "num:$1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.