Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string with part of the matching regex

Tags:

java

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);
like image 414
varunl Avatar asked Jun 02 '12 21:06

varunl


People also ask

How do you replace a section of a string in regex?

The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.

How do I replace a word in a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Does string replace take regex?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.


1 Answers

Like this:

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

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

like image 144
Jirka Hanika Avatar answered Oct 02 '22 12:10

Jirka Hanika