Java regex to strip out XML tags, but not tag contents

java, regex, string, xml

Solution

"How now <fizz>brown</fizz> cow.".replaceAll("<[^>]+>", "")

Problem

I have the following Java code: ``` str = str.replaceAll("<.*?>.*?</.*?>|<.*?/>", ""); ``` This turns a String like so: ``` How now <fizz>brown</fizz> cow. ``` Into: ``` How now cow. ``` However, I want it to just strip the `<fizz>` and `</fizz>` tags, or just standalone `</fizz`> tags, and leave the element's content alone. So, a regex that would turn the above into: ``` How now brown cow. ``` Or, using a more complex String, somethng that turns: ``` How <buzz>now <fizz>brown</fizz><yoda/></buzz> cow. ``` Into: ``` How now brown cow. ``` I tried this: ``` str = str.replaceAll("<.*?></.*?>|<.*?/>", ""); ``` And that doesn't work at all. Any ideas? Thanks in advance!

Original source

Related problems