podeig
podeig

Reputation: 2741

How to remove a tag with regex

I have such string:

<span class="cDkSuggestion"></span>
<var class="tSuggestionTag r5">representation</var>
<span class="ib p1 tSuggetionName">for<b>rep</b>resentation</span>
<var class="tSuggestionTag r5">for<b>rep</b>res...</var>
<var class="tSuggestionTag r5">cost of representation</var>

and regex

query = query.replace(/<var.*>(.*)<\/var>/gi, "");

result of this regex is

<span class="cDkSuggestion"></span>

I need

<span class="cDkSuggestion"></span>
<span class="ib p1 tSuggetionName">for<b>rep</b>resentation</span>

How to check in regex that does not includes others tags in replacing?

Upvotes: 0

Views: 67

Answers (2)

Mainak
Mainak

Reputation: 3

If you know the text contains only tags, you can use this:

String test = testString.replaceAll("(?i)]*>", "");

For example, if the input string were SomethingAnother Thing, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String test = testString.replaceAll("(?i)]*>", " ").replaceAll("\s+", " ").trim();

Upvotes: -1

Toto
Toto

Reputation: 91518

You really should use a parser, but if you want a regex, make it not greedy:

/<var.*?>(.*?)<\/var>/gi

or, safer:

/<var[^>]*>([^<]*)<\/var>/gi

Upvotes: 2

Related Questions