2015-12-21 74 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