gpt4 book ai didi

java - 查找字符串中打开关闭的 html 标签的数量

转载 作者:行者123 更新时间:2023-12-04 08:59:13 25 4
gpt4 key购买 nike

我试图找出查找字符串中有效 HTML 标签数量的最佳方法。

假设标签只有在有开始和结束标签时才有效

这是一个测试用例的例子

INPUT

"html": "<html><head></head><body><div><div></div></div>"

Output

"validTags":3

最佳答案

如果需要解析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>")

关于java - 查找字符串中打开关闭的 html 标签的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63632799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com