Replace the string with the part of the corresponding regular expression

I have a long string. I want to replace all matches with the part of the corresponding regular expression (group).

For instance:

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" with, say, "<h1>is</h1>" . The case should remain the same as the original. So the last line 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 that I tried:

 Pattern pattern = Pattern.compile("[.>, ](is)[.<, ]", Pattern.CASE_INSENSITIVE); 
+6
source share
6 answers

The Matcher class is commonly used in combination with Pattern . Use the Matcher.replaceAll() method to replace all matches in a 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 the word boundary (for example, a space). This is useful for matching only the words "there", not words containing the letters "i" and "s" (for example, "island").

+10
source

Like this:

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

$1 refers to text shot by group # 1 in your regular expression.

+4
source

Michael's answer is better, but if you accidentally want only [.>, ] And [.<, ] As borders, 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>"); 
+3
source
 yourStr.replaceAll("(?i)([.>, ])(is)([.<, ])","$1<h1>$2</h1>$3") 

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

+1
source

Just use the backlink for this.

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

0
source

It may be a late addition, but if someone is looking for it like
The search for 'thing' , and also he needs โ€œSomethingโ€ to be accepted as a result,

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

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

0
source

Source: https://habr.com/ru/post/917264/


All Articles