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

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

本文介绍了用匹配的正则表达式的一部分替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串很长.我想用匹配的正则表达式(组)的一部分替换所有匹配项.

I have a long string. I want to replace all the matches with part of the matching regex (group).

例如:

String = "This is a great day, is it not? If there is something, THIS IS it. <b>is</b>".

我想用< h1> is</h1>" 替换所有单词"is" .案件应与原案相同.所以我想要的最后一个字符串是:

I want to replace all the words "is" by, let's say, "<h1>is</h1>". The case should remain the same as original. So the final string I want is:

This <h1>is</h1> a great day, <h1>is</h1> it not? If there <h1>is</h1> something,
THIS <h1>IS</h1> it. <b><h1>is</h1></b>.

我正在尝试的正则表达式:

The regex I was trying:

Pattern pattern = Pattern.compile("[.>, ](is)[.<, ]", Pattern.CASE_INSENSITIVE);

推荐答案

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

这篇关于用匹配的正则表达式的一部分替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:26