且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用匹配的正则表达式的一部分替换字符串

更新时间:2022-11-11 23:14:41

Matcher 类通常与 Pattern 结合使用.使用 Matcher.replaceAll()方法替换字符串中的所有匹配项

The Matcher class is commonly used in conjunction with Pattern. Use the Matcher.replaceAll() method to replace all matches in the string

String str = "This is a great day...";
Pattern p = Pattern.compile("\\bis\\b", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
String result = m.replaceAll("<h1>is</h1>");

注意:使用 \ b regex命令将在单词边界(例如空格)上匹配.这有助于确保仅匹配单词"is",而不匹配包含字母"i"和"s"(例如"island")的单词.

Note: Using the \b regex command will match on a word boundary (like whitespace). This is helpful to use in order to ensure that only the word "is" is matched and not words that contain the letters "i" and "s" (like "island").