Java에서 정규 표현식으로 html 태그 제거

2142 단어 java정칙html태그
자바에서 정규 표현식은 html의 라벨을 제거하는데 주요 목적은 더욱 정확한 내용을 표시하는 것이다. 예를 들어 얼마 전에 블로그에서 글을 발표하는 것과 같은 기능을 했다. 편집기에서 내용을 입력하면 스타일 라벨도 백그라운드에 전송하고 데이터베이스에 저장된다. 그러나 요약을 표시할 때 본문을 표시하는 50자를 요약으로 하면 모든 html 라벨을 제거하고 50자를 캡처해야 한다.그래서 자바 정규 표현식을 통해 다음과 같은 방법을 실현했다. 코드는 다음과 같다.
주: 이것은 자바 정규 표현식으로 html 라벨을 제거하는 방법입니다.

private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //  script 
  private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //  style 
  private static final String regEx_html = "<[^>]+>"; //  HTML 
  private static final String regEx_space = "\\s*|\t|\r|
";// private static final String regEx_w = "<w[^>]*?>[\\s\\S]*?<\\/w[^>]*?>";// w /** * @param htmlStr * @return Html * @author LongJin */ public static String delHTMLTag(String htmlStr) { Pattern p_w = Pattern.compile(regEx_w, Pattern.CASE_INSENSITIVE); Matcher m_w = p_w.matcher(htmlStr); htmlStr = m_w.replaceAll(""); // script Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // script Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // style Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // html Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE); Matcher m_space = p_space.matcher(htmlStr); htmlStr = m_space.replaceAll(""); // htmlStr = htmlStr.replaceAll(" ", ""); // return htmlStr.trim(); // }
ps: 방법은 참고만 제공하여 모두가 함께 공부할 수 있도록 합니다. 부족하거나 의문이 있으면 평론을 환영합니다.

좋은 웹페이지 즐겨찾기