Is there a way to determine if a string contains HTML tags in java

Is there any predefined method indicating whether a string contains HTML tags or characters?

+4
source share
3 answers

You can try regular expressions like

private static final String HTML_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; private Pattern pattern = Pattern.compile(HTML_PATTERN); public boolean hasHTMLTags(String text){ Matcher matcher = pattern.matcher(text); return matcher.matches(); } 
+2
source

Use regex to search or identify HTML tags in String.

 boolean containsHTMLTag = stringHtml.matches(".*\\<[^>]+>.*"); 

Or as Tim suggested using Jsoup as shown below: -

 String textOfHtmlString = Jsoup.parse(htmlString).text(); boolean containedHTMLTag = !textOfHtmlString.equals(htmlString); 
+1
source

You should use find ()

 private static final String HTML_TAG_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; static Pattern htmlValidator = TextUtils.isEmpty(HTML_TAG_PATTERN) ? null:Pattern.compile(HTML_TAG_PATTERN); public static boolean validateHtml(final String text){ if(htmlValidator !=null) return htmlValidator.matcher(text).find(); return false; } 
0
source

All Articles