Java: regular expression replacement
•
Java
I have this string:
foo bar 567 baz
Now I want to add string num:. Before each number So the result must be:
foo bar num:567 baz
This must also work:
foo 73761 barbazboom!! 87 result: foo num:73761 barbazboom!! num:87
The regular expression for the search number is: [0-9], but I want to replace the matching substring with num: [matching substring]
Now I've written an example in numbers, but another example can be: add e-mail before each e-mail address:
Solution
Use grouping You can define a group using parentheses (and) 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");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码