stix
stix

Reputation: 110

Rebuild dynamically html tag when splitted

I need to split my html into two parts when a particular variable appears.

Here's an example:

<h1>I can have any kind of text here</h1>
<p>&nbsp;</p>
<p><em><strong>When I see this variable :)</strong> I want to rebuild my html.</em></p>

What I would like at the end:

<h1>I can have any kind of text here</h1>
<p>&nbsp;</p>
<p><em><strong>When I see this</strong></em></p>

<p><em><strong> :)</strong> I want to rebuild my html.</em></p>

Here is what I thought (tell me if there is a better way):

  1. Split on my variable
  2. Get all tags by a regex? (I just know regex to tell me true or false)
  3. Put all tags unclosed on a stack?
  4. loop twice (array split 1 and array split 2)

EDIT Example 2 :

<ol>
<li>
<h2>I can have any kind of text here 1</h2>
</li>
<li>
<h2><strong>I can have any kind of text here 2 variable</strong></h2>
</li>
<li>
<h2><strong>I can have any kind of text here 3</strong></h2>
</li>
<li>
<h2>I can have any kind of text here 4</h2>
</li>
<li><em><strong>When I see this</strong></em></li>
</ol>
<p>&nbsp;</p>

...

<ol>
<li>
<h2>I can have any kind of text here 1</h2>
</li>
<li>
<h2><strong>I can have any kind of text here 2 variable </strong></h2>
</li>
</ol>

Variable

<ol>
<li>
<h2><strong>I can have any kind of text here 3</strong></h2>
</li>
<li>
<h2>I can have any kind of text here 4</h2>
</li>
<li><em><strong>When I see this</strong></em></li>
</ol>
<p>&nbsp;</p>

Exemple 3 :

<p><a href="test">I can have any kind of text of varaible here even clickable.</a></p>

...

<p><a href="test">I can have any kind of text of</a></p>

varaible

<p><a href="test">here even clickable.</a></p>

Upvotes: 1

Views: 75

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 30995

It's well known that you should use a html parser instead a regex.

Anyway, you can use a simple string replaceAll to do what you want. If you want to use a regex you can just use something like this:

String str = "<h1>I can have any kind of text here</h1>\n<p>&nbsp;</p>\n<p><em><strong>When I see this variable :)</strong> I want to rebuild my html.</em></p>\n"; 
str = str.replaceAll("variable", "</strong></em></p>\n<p><em><strong>"); 
System.out.println(str);

Working regex

IdeOne demo

Output

<h1>I can have any kind of text here</h1>
<p>&nbsp;</p>
<p><em><strong>When I see this </strong></em></p>
<p><em><strong> :)</strong> I want to rebuild my html.</em></p>

Upvotes: 1

Related Questions