정규식 정규식 사용예제 [1]

황제낙엽 2008.06.11 13:48 조회 수 : 2296 추천:174

1. 기본예제
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * 정규표현식 기본 사용 예제   
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest01 {   
  12.   
  13.     public static void main(String[] args) {   
  14.   
  15.         Pattern p = Pattern.compile("a*b");   
  16.         Matcher m = p.matcher("aaaaab");   
  17.         boolean b = m.matches();   
  18.            
  19.         if (b) {   
  20.             System.out.println("match");   
  21.         } else {   
  22.             System.out.println("not match");   
  23.         }   
  24.     }   
  25. }  
결과값 : match

2. 문자열 치환하기
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * 문자열 치환 예제  
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest02 {   
  12.   
  13.     public static void main(String[] args) {   
  14.   
  15.         Pattern p = Pattern.compile("cat");   
  16.         Matcher m = p.matcher("one cat two cats in the yard");   
  17.            
  18.         StringBuffer sb = new StringBuffer();   
  19.         while (m.find()) {   
  20.             m.appendReplacement(sb, "dog");   
  21.         }   
  22.         m.appendTail(sb);   
  23.         System.out.println(sb.toString());   
  24.            
  25.         // or   
  26.         //String str = m.replaceAll("dog");   
  27.         //System.out.println(str);   
  28.     }   
  29. }  
결과값 : one dog two dogs in the yard

3. 이메일 주소 유효검사
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * 이메일주소 유효검사  
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest03 {   
  12.        
  13.     public static boolean isValidEmail(String email) {   
  14.         Pattern p = Pattern.compile("^(?:w+.?)*w+@(?:w+.)+w+$");   
  15.         Matcher m = p.matcher(email);   
  16.         return m.matches();   
  17.     }   
  18.   
  19.     public static void main(String[] args) {   
  20.            
  21.         String[] emails = { "test@abc.com", "a@.com", "abc@mydomain" };   
  22.            
  23.         for (int i = 0; i < emails.length; i ++) {   
  24.             if (isValidEmail(emails[i])) {   
  25.                 System.out.println(emails[i]);   
  26.             }   
  27.         }   
  28.     }   
  29. }  
결과값 : test@abc.com

4. HTML 태그 제거
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * HTML 태그 제거  
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest04 {   
  12.   
  13.     public static String stripHTML(String htmlStr) {   
  14.         Pattern p = Pattern.compile("<(?:.|s)*?>");   
  15.         Matcher m = p.matcher(htmlStr);   
  16.         return m.replaceAll("");   
  17.     }   
  18.        
  19.     public static void main(String[] args) {   
  20.         String htmlStr = "<html><body><h1>Java2go.net</h1>"  
  21.             + " <p>Sehwan@Noh's Personal Workspace...</p></body></html>";   
  22.         System.out.println(stripHTML(htmlStr));           
  23.     }   
  24. }  
결과값 : Java2go.net Sehwan@Noh's Personal Workspace...

5. HTML 링크 만들기
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * HTML 링크 만들기  
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest05 {   
  12.   
  13.     public static String linkedText(String sText) {   
  14.         Pattern p = Pattern.compile(   
  15.                 "(http|https|ftp)://[^s^.]+(.[^s^.]+)*");   
  16.         Matcher m = p.matcher(sText);   
  17.   
  18.         StringBuffer sb = new StringBuffer();   
  19.         while (m.find()) {   
  20.             m.appendReplacement(sb,    
  21.                     "<a href='" + m.group()+"'>" + m.group() + "</a>");   
  22.         }   
  23.         m.appendTail(sb);   
  24.   
  25.         return sb.toString();   
  26.     }       
  27.            
  28.     public static void main(String[] args) {           
  29.         String strText =    
  30.                 "My homepage URL is http://www.java2go.net/home/index.html.";   
  31.         System.out.println(linkedText(strText));   
  32.     }   
  33. }  
결과값 : My homepage URL is <a href='http://www.java2go.net/index.html'>http://www.java2go.net/index.html</a>.

6. 금지어 필터링 하기
·미리보기 | 소스복사·
  1. import java.util.regex.Matcher;   
  2. import java.util.regex.Pattern;   
  3.   
  4. /**  
  5.  * 금지어 필터링하기  
  6.  *   
  7.  * @author   Sehwan Noh <sehnoh@gmail.com>  
  8.  * @version  1.0 - 2006. 08. 22  
  9.  * @since    JDK 1.4  
  10.  */  
  11. public class RegExTest06 {   
  12.        
  13.     public static String filterText(String sText) {   
  14.         Pattern p = Pattern.compile("fuck|shit|개새끼", Pattern.CASE_INSENSITIVE);   
  15.         Matcher m = p.matcher(sText);   
  16.   
  17.         StringBuffer sb = new StringBuffer();   
  18.         while (m.find()) {   
  19.             //System.out.println(m.group());   
  20.             m.appendReplacement(sb, maskWord(m.group()));   
  21.         }   
  22.         m.appendTail(sb);   
  23.            
  24.         //System.out.println(sb.toString());   
  25.         return sb.toString();   
  26.     }   
  27.        
  28.     public static String maskWord(String word) {   
  29.         StringBuffer buff = new StringBuffer();   
  30.         char[] ch = word.toCharArray();   
  31.         for (int i = 0; i < ch.length; i++) {   
  32.             if (i < 1) {   
  33.                 buff.append(ch[i]);   
  34.             } else {   
  35.                 buff.append("*");   
  36.             }   
  37.         }   
  38.         return buff.toString();   
  39.     }   
  40.        
  41.     public static void main(String[] args) {   
  42.         String sText = "Shit! Read the fucking manual. 개새끼야.";           
  43.         System.out.println(filterText(sText));   
  44.     }   
  45. }  
결과값 : S***! Read the f***ing manual. 개**야.

번호 제목 글쓴이 날짜 조회 수
347 java.util.Optional 에서의 map() 함수의 이해 황제낙엽 2026.06.24 666
346 linux(ubuntu) 의 jdk 21 이 설정된 환경에서 jdk 17 로 다운그레이드 절차 황제낙엽 2025.09.22 1532
345 [ChatGPT] javax.* 패키지와 jakarta.* 패키지의 혼합 사용 방안 황제낙엽 2025.04.15 2458
344 [ChatGPT] *.servlet.http.HttpServlet 클래스를 사용할 수 있는 주요 WAS 목록 황제낙엽 2025.04.14 2038
343 [ChatGPT] JDBC API에서 java.sql과 javax.sql 패키지의 차이점 황제낙엽 2025.01.31 2218
342 jakarta.servlet 패키지를 이용한 File Upload 구현 (2024.03.03, Servlet 5.0) 황제낙엽 2025.01.02 2310
341 [ChatGPT] Java EE가 Jakarta EE로 전환 황제낙엽 2025.01.01 2525
340 [ChatGPT] File.delete() 함수로 파일 삭제가 되지 않는 경우 황제낙엽 2024.12.10 2809
339 [ChatGPT] <jsp:include>에서 flush="true"를 설정시의 몇 가지 문제점 과 대안 황제낙엽 2024.07.19 2493
338 [Copilot] JSP, Servlet, web.xml, mysql 한글 설정 황제낙엽 2024.07.12 2555
337 Base64 클래스의 encode, decode 에서 URL-safe 황제낙엽 2024.07.10 2624
336 [Copilot] JSP 에서 다른 페이지를 현재 페이지에 포함시키는 문법 (include) 황제낙엽 2024.06.26 2570
335 Exception 출력에 대한 고찰 황제낙엽 2024.06.10 2198
334 google-auth-library-oauth2-http 라이브러리 다운로드 황제낙엽 2023.11.19 4025
333 firebase-admin-java 라이브러리 다운로드 (firebase admin sdk library) 황제낙엽 2023.11.19 2805
332 Enum 활용 (개인블로그, Effective Java) file 황제낙엽 2023.11.02 2759
331 Enum 활용 (우아한기술블로그) file 황제낙엽 2023.11.02 2790
330 servlet name 에 camel case 를 사용해서는 안되는 이유 황제낙엽 2023.10.24 2508
329 org.apache.commons.fileupload.servlet.ServletFileUpload 이용 예시 황제낙엽 2023.08.25 3336
328 ServletFileUpload.parseRequest() 실행 결과 리스트가 비어있는 오류 황제낙엽 2023.08.25 2935