2015-12-21 40 views
1

当出现特定变量时,我需要将我的html分成两部分。拆分时动态重建html标记

下面是一个例子:

<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> 

我想在最后什么:

<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> 

这是我想(告诉我,如果有更好的方法):

  1. 在我的变量上分割
  2. 通过正则表达式获取所有标记? (我只是知道正则表达式来告诉我是真是假)
  3. 把所有的标签都放在堆栈上?
  4. 循环两次(阵列分割1和阵列分开2)

EDIT实施例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> 

可变

<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> 

为例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> 
+6

第5步:忘记第1步 - 4并改用解析器? – Jan

+0

的确有很多html解析器。 –

回答

1

这是众所周知的是,你应该使用HTML解析器,而不是一个正则表达式

无论如何,你可以使用一个简单的字符串replaceAll来做你想做的。如果你想使用正则表达式你可以使用这样的事情:

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

输出

<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> 
+1

但是html是未知的/动态的。所以我不能用静态标签 – stix

+0

替换它@maxxy在这种情况下,你可以发布一个额外的例子吗? –

+1

我刚刚编辑我的帖子。 Thx为您提供帮助。根据我的例子,为什么我想到堆栈(但可能是一个更好的方法?) – stix