Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string inside tags?

Tags:

java

regex

I want to replace a content inside some tags, eg:

<p>this it to be replaced</p>

I could extract the content between with groups like this, but can i actually replace the group?

str = str.replaceAll("<p>([^<]*)</p>", "replacement");
like image 456
membersound Avatar asked Jun 21 '12 12:06

membersound


People also ask

How do I replace text in a string in HTML?

The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string. It searches for a string corresponding to either a particular value or regular expression and returns a new string with the modified values.

How do you replace inside a string?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.

How do you remove tag strings?

The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.

What is replace () in JavaScript?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.


1 Answers

Change the regex to this:

(?<=<p>).*?(?=</p>)

ie

str = str.replaceAll("(?<=<p>).*?(?=</p>)", "replacement");

This uses a "look behind" and a "look ahead" to assert, but not capture, input before/after the matching (non-greedy) regex

Just in case anyone is wondering, this answer is different to dacwe's: His uses unnecessary brackets. This answer is the more elegant :)

like image 67
Bohemian Avatar answered Nov 15 '22 14:11

Bohemian