[英]Check a string is contain HTML tag or just plain text
我想檢查包含 HTML 標簽或純文本的消息文本? 是否有任何庫或實用程序?
IE:
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
您是否考慮過使用正則表達式?
使用類似(\\<\\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("I'm a <tag>HTML</tag>.");
System.out.println(matcher.matches() ? "HTML" : "plain text")
我在正則表達式字符串的前端和末尾添加了.*
以符合Pattern API,它將在文本String
中找到標簽,因此需要能夠在一行文本中沒有前導 html 和沒有結束 html匹配正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.