检查一个字符串是否包含HTML标签或者只是纯文本

huangapple go评论59阅读模式
英文:

Check a string is contain HTML tag or just plain text

问题

我想检查包含HTML标签的消息文本,还是只有纯文本?

是否有任何库或工具?

即:

我是文本 & 我是数字 => 纯文本

我是文本 => 纯文本

我是 HTML。 => HTML

我是 HTML 。 => HTML

英文:

I want to check a message text that contains HTML tags or just a plain text?
Is there any library or utility?

i.e:

I'm a text & I'm a number => plain text

I'm a text => plain text

I'm a <tag>HTML</tag>. => HTML 

I'm a HTML <tag/>. => HTML

答案1

得分: 1

你有考虑过使用正则表达式吗?

类似使用 (\<\w*)((\s\/\>)|(.*\<\/\w*\>)) 或者 (\<\w*)[\s\w\=\"\-]+((\/>)|(\s*\>)|(.*\<\/\w*\>))?[\s\w]+((<\/\w+>))? 可能能够涵盖常见情况。

你可以使用 java.util.regex

Pattern pattern = Pattern.compile(".*(\\<\\w*)[\\s\\w\\=\\\"\\-]+((\\/>)|(\\s*\\>)|(.*\\<\\/\\w*\\>))?[\\s\\w]+((<\\/\\w+>)).*");
Matcher matcher = pattern.matcher("我是一个 <tag>HTML</tag>。");
System.out.println(matcher.matches() ? "HTML" : "纯文本")

我在正则表达式字符串的开头和结尾添加了 .*,以便与 Pattern API 兼容,该 API 将在文本字符串中查找标签,因此需要能够在文本行中没有前导 HTML 和没有结束 HTML 的情况下匹配正则表达式。

英文:

Have you looked into using regex?

Using something like (\<\w*)((\s\/\>)|(.*\<\/\w*\>)) or (\<\w*)[\s\w\=\"\-]+((\/>)|(\s*\>)|(.*\<\/\w*\>))?[\s\w]+((<\/\w+>))? could most likely cover common cases.

You could use java.util.regex

Pattern pattern = Pattern.compile(".*(\\<\\w*)[\\s\\w\\=\\\"\\-]+((\\/>)|(\\s*\\>)|(.*\\<\\/\\w*\\>))?[\\s\\w]+((<\\/\\w+>)).*");
Matcher matcher = pattern.matcher("I'm a <tag>HTML</tag>.");
System.out.println(matcher.matches() ? "HTML" : "plain text")

I added .* to the front and end of the regex expression string for the compliance with Pattern API that will find the tags within a String of text and so needs to be able to have none leading html and none ending html in a line of text to match the regex expression.

huangapple
  • 本文由 发表于 2020年9月29日 01:45:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64107095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定