如果需要解析 HTML
不要自己动手。没有必要重新发明轮子。有大量用于解析 HTML 的库。为正确的工作使用正确的工具。
将精力集中在项目的其余部分上。当然,您可以实现自己的函数来解析字符串,查找< 和>,并采取适当的行动。但是 HTML 可能比您想象的要复杂一些,或者您最终可能需要更多的 HTML 解析,而不仅仅是计算标签。
也许将来您还想计算<br/> 和<br />。或者你会想要找到 HTML 树的深度。
也许您的自制代码没有考虑转义字符、嵌套标签等所有可能的组合。字符串中有多少正确的标签:
<a><b><c><d e><f g="<h></h>"><i j="<k>" l="</k>"></i></f></e d></b></c></ a >
在评论中,用户 dbl 链接到一个类似的问题,其中包含指向库的链接:How to validate HTML from java ?
如果你想把开闭标签对算作一个学习项目
这是一个用伪代码提出的算法,作为递归函数:
function count_tags(s):
tag, remainder = find_next_tag(s)
found, inside, after = find_closing_tag(tag, remainder)
if (found)
return 1 + count_tags(inside) + count_tags(after)
else
return count_tags(inside)
示例
- 在字符串
hello <a>world<c></c></a><b></b>上,我们会得到:
tag = "<a>"
remainder = "world<c></c></a><b></b>"
found = true
inside = "world<c></c>"
after = "<b></b>"
return 1 + count_tags("world<c></c>") + count_tags("<b></b>")
- 在字符串
<html><head></head>:
tag = "<html>"
remainder = "<head></head>"
found = false
inside = "<head></head>"
after = ""
return count_tags("<head></head>")
- 在字符串
<a><b></a></b>:
tag = "<a>"
remainder = "<b></a></b>"
found = true
inside = "<b>"
after = "</b>"
return 1 + count_tags("<b>") + count_tags("</b>")