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

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

sitelink1 http://blog.naver.com/chahojun?Redirect=...m/cuteshim 
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  
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. 개**야.

번호 제목 글쓴이 날짜 조회 수
126 File 생성시 encoding 지정하기 (Unicode/utf-8 file 읽고 쓰기) 황제낙엽 2008.05.22 1002
125 java String.replaceAll (String regex, String replacement) 쓸떄 조심할 것 황제낙엽 2008.05.22 720
124 java String.replaceAll 잘쓰기 황제낙엽 2008.05.22 750
123 간단한 DBConnection 프로그램 (JDBC) file 황제낙엽 2008.05.15 801
122 상속과 연관(association, composition) 황제낙엽 2008.04.10 580
121 HttpServletRequest 객체의 함수 모음 file 황제낙엽 2008.01.28 772
120 ObjectCache클래스 와 Server/Client프로그램 file 황제낙엽 2007.11.07 610
119 ObjectCache시스템의 구현을 위한 추가 고려사항 황제낙엽 2007.11.04 581
118 문제 : 간단한 ObjectCache 프로그램을 구현하라 황제낙엽 2007.11.01 692
117 ObjectCache 클래스를 구현한 예제 소스 파일들 황제낙엽 2007.11.01 555
116 LinkedHashMap 를 이용한 LRU 캐쉬 구현 황제낙엽 2007.11.03 859
115 J2SE 5.0 에서의 QUEUE와 DELAYED 프로세싱 황제낙엽 2007.11.02 598
114 J2EE object-caching frameworks (ObjectCache) 황제낙엽 2007.11.02 2688
113 Object Caching in a Web Portal Application Using JCS (ObjectCache) 황제낙엽 2007.11.02 634
112 Java Object Cache | Patterns 'N J2EE (ObjectCache) 황제낙엽 2007.11.01 725
111 Runtime 클래스를 이용한 JVM 메모리 사용량 확인 황제낙엽 2007.11.05 613
110 자바 애플리케이션에서 동적으로 PDF 파일 생성하기 황제낙엽 2007.10.03 589
109 싱글사인온(single sign-on)으로 엔터프라이즈 자바 인증을 단순하게! 황제낙엽 2007.10.03 586
108 [BPP] 게시판 페이징 로직 분석 - M1.3 file 황제낙엽 2007.09.26 488
107 [HttpURLConnection] 2초후에 연결 끊어주는 URLConnection 예제 황제낙엽 2007.09.08 652