Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 트랜잭션
- 명령어
- Javascript
- PostgreSQL
- Python
- spring
- oracle
- 자바
- docker
- github
- 추상클래스
- mssql
- MariaDB
- 티스토리챌린지
- rsync
- 오블완
- DBMS
- IntelliJ
- group by
- SQL
- JPA
- 호이스팅
- pandas
- Linux
- git
- 리눅스
- java
- analytics4
- MongoDB
- mysql
Archives
- Today
- Total
hanker
JAVA - HTML String값 특정 태그 변경 본문
반응형
HTML언어를 문자열로 받을 때, 태그 열고 닫는 태그가 있어서 replace 문자열 변경이 수월하진 않다.
변경하는 방법을 찾아보자.
1. 정규식 사용
- 시작 태그와 끝나는 꺽새(>) 를 찾아서 그 안에 있는 내용들이랑 같이 삭제한다.
public static void main(String[] args) throws Exception {
String html = "<html><header></header><body><div>안녕하세요</div><img src=\"/images/google.png\" alt=\"Google\" /></body></html>";
String regExp = "<img[^>]*>";
System.out.println(html.replaceAll(regExp, ""));
}
결과
2. JSOUP 라이브러리 사용
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
pom.xml에 라이브러리 추가
public static void main(String[] args) throws Exception {
String html = "<html><header></header><body><div>안녕하세요</div><img src=\"/images/google.png\" alt=\"Google\" /></body></html>";
// HTML을 Document 객체로 파싱
Document doc = Jsoup.parse(html);
// <img> 태그를 전체 제거
Elements imgTags = doc.select("img");
for (Element img : imgTags) {
img.remove();
}
System.out.println(doc.html());
}
결과.
반응형
'JAVA' 카테고리의 다른 글
JAVA - HttpUrlConnection, HttpsUrlConnection (httpMethod GET, POST) (1) (0) | 2024.09.11 |
---|---|
JAVA - HttpUrlConnection, HttpsUrlConnection (0) | 2024.09.10 |
JAVA - 단일 역슬래시, 역슬래시 뒤 숫자 없애기 (1) | 2024.09.06 |
JAVA - Timestamp to String (13자리) (0) | 2024.09.03 |
JAVA - Entity to Map, Map to Entity (0) | 2024.09.01 |