简体   繁体   中英

Replace string with part of the matching regex

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

For example:

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

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);

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

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

Like this:

str = str.replaceAll(yourRegex, "<h1>$1</h1>");

The $1 refers to the text captured by group #1 in your regex.

Michael's answer is better, but if you happen to specifically only want [.>, ] and [.<, ] as boundaries, you can do it like this:

String input = "This is a great day, is it not? If there is something, THIS IS it. <b>is</b>";
Pattern p = Pattern.compile("(?<=[.>, ])(is)(?=[.<, ])", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
String result = m.replaceAll("<h1>$1</h1>");
yourStr.replaceAll("(?i)([.>, ])(is)([.<, ])","$1<h1>$2</h1>$3")

(?i) to indicate ignoring case; wrap everything your want to reuse with brackets, reuse them with $1 $2 and $3, concatenate them into what you want.

Simply use a backreference for that.

"This is a great day, is it not? If there is something, THIS IS it. <b>is</b>".replaceAll("[.>, ](is)[.<, ]", "<h1>$2</h1>"); should do.

It may be a late addition, but if anyone is looking for this like
Searching for and also he needs 'Something' too to be taken as result, 并且他也需要“东西”才能被视为结果,

Pattern p = Pattern.compile("([^ ] )is([^ \\.] )");
String result = m.replaceAll("<\\h1>$1is$2</h1>");

will result <\\h1>Something</h1> too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM