varunl
varunl

Reputation: 20229

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

Upvotes: 15

Views: 29567

Answers (6)

Polygnome
Polygnome

Reputation: 7795

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.

Upvotes: 0

Luckie
Luckie

Reputation: 31

It may be a late addition, but if anyone is looking for this like Searching for thing 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 Something too

Upvotes: 0

nichijou
nichijou

Reputation: 504

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.

Upvotes: 2

Sean Fujiwara
Sean Fujiwara

Reputation: 4546

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

Upvotes: 3

Michael
Michael

Reputation: 35341

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

Upvotes: 15

Jirka Hanika
Jirka Hanika

Reputation: 13529

Like this:

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

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

Upvotes: 13

Related Questions