【问题标题】:Rebuild dynamically html tag when splitted拆分时动态重建html标签
【发布时间】:2016-03-27 21:20:24
【问题描述】:

当出现特定变量时,我需要将我的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)

编辑示例 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>

变量

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

【问题讨论】:

  • 第 5 步:忘记第 1-4 步,改用解析器?
  • 确实有很多 html 解析器。

标签: java html regex tags


【解决方案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>

【讨论】:

  • 但是 html 是未知/动态的。所以我不能用静态标签替换它
  • @maxxy 在这种情况下,您可以再发布一个示例吗?
  • 我刚刚编辑了我的帖子。谢谢你的帮助。根据我的例子,我为什么想到堆栈(但可能是更好的方法?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多