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

황제낙엽 2008.06.11 13:54 조회 수 : 384 추천:179

sitelink1  
sitelink2  
sitelink3 http://1 
sitelink4 http://ko 
sitelink5 http://blog.naver.com/maru0226?Redirect=...0006922656 
sitelink6 http://sitelink1 
Example Regex Scenarios
아래 코드는 J2SE 1.4 도큐먼트의 예제를 완성한 것이다.
 
/*
* 이 코드는 "One dog, two dogs in the yard." 라는 문자열을
* 표준 출력을 통해 출력한다.
*/
import java.util.regex.*;
 
public class Replacement {
   public static void main(String[] args) throws Exception {
       // ‘cat’이라는 패턴 생성
       Pattern p = Pattern.compile("cat");

       // 입력 문자열과 함께 매쳐 클래스 생성
       Matcher m = p.matcher("one cat," + " two cats in the yard");
       StringBuffer sb = new StringBuffer();
       boolean result = m.find();

       // 패턴과 일치하는 문자열을 ‘dog’으로 교체해가며
       // 새로운 문자열을 만든다.
       while(result) {
           m.appendReplacement(sb, "dog");
           result = m.find();
       }
       // 나머지 부분을 새로운 문자열 끝에 덫붙인다.
       m.appendTail(sb);
       System.out.println(sb.toString());
   }
}
 
메일 주소 포맷 확인
다음 코드는 주어진 입력 시퀀스가 메일 주소 포맷인가를 판단한다. 이 코드는 가능한 모든 형태의 메일 주소를 확인하는 것은 아니니 필요하면 코드를 더 추가해 사용하자.
 
/*
* 메일 주소에서 잘못된 문자 검사
*/
public class EmailValidation {
  public static void main(String[] args) throws Exception {
                               
     String input = "@sun.com";
     //메일 주소가 ‘.’이나 ‘@’와 같은 잘못된 문자로 시작하는 지 확인
     Pattern p = Pattern.compile("^.|^@");
     Matcher m = p.matcher(input);
     if (m.find())
        System.err.println("Email addresses don't start" + " with dots or @ signs.");
     //’www.’으로 시작하는 주소를 찾는다.
     p = Pattern.compile("^www.");
     m = p.matcher(input);
     if (m.find()) {
       System.out.println("Email addresses don't start" + " with "www.", only web pages do.");
     }
     p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
     m = p.matcher(input);
     StringBuffer sb = new StringBuffer();
     boolean result = m.find();
     boolean deletedIllegalChars = false;
 
     while(result) {
        deletedIllegalChars = true;
        m.appendReplacement(sb, "");
        result = m.find();
     }
 
     m.appendTail(sb);
 
     input = sb.toString();
 
     if (deletedIllegalChars) {
        System.out.println("It contained incorrect characters" + " , such as spaces or commas.");
     }
  }
}
 
파일에서 제어 문자 제거
 
/*
* 지정된 파일에서 제어 문제를 찾아 제거한다.
*/
import java.util.regex.*;
import java.io.*;
 
public class Control {
   public static void main(String[] args) throws Exception {
                               
       //파일 객체 생성
       File fin = new File("fileName1");
       File fout = new File("fileName2");
       //입출력 스트림 생성
       FileInputStream fis = new FileInputStream(fin);
       FileOutputStream fos = new FileOutputStream(fout);
 
       BufferedReader in = new BufferedReader (new InputStreamReader(fis));
       BufferedWriter out = new BufferedWriter (new OutputStreamWriter(fos));
 
       // 제어문자를 의미하는 패턴 생성
       Pattern p = Pattern.compile("{cntrl}");
       Matcher m = p.matcher("");
       String aLine = null;
       while((aLine = in.readLine()) != null) {
           m.reset(aLine);
           //제어 문자들을 빈 문자열로 대체
           String result = m.replaceAll("");
           out.write(result);
           out.newLine();
       }
       in.close();
       out.close();
   }
}
 
파일 검색
 
/*
* .java 파일에서 주석을 찾아 출력한다.
*/
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
 
public class CharBufferExample {
   public static void main(String[] args) throws Exception {
       // 주석을 나타내는 패턴 생성
       Pattern p = Pattern.compile("//.*$", Pattern.MULTILINE);
      
       // 소스파일
       File f = new File("Replacement.java");
       FileInputStream fis = new FileInputStream(f);
       FileChannel fc = fis.getChannel();
      
       // 소스 파일로부터 CharBuffer 생성
       ByteBuffer bb = fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
       Charset cs = Charset.forName("8859_1");
       CharsetDecoder cd = cs.newDecoder();
       CharBuffer cb = cd.decode(bb);
      
       // 매칭 작업 수행
       Matcher m = p.matcher(cb);
       while (m.find())
           System.out.println("Found comment: "+m.group());
   }
}

번호 제목 글쓴이 날짜 조회 수
143 숫자 에 대응 되는 패턴의 형식화 #1 황제낙엽 2008.07.08 359
142 숫자를 통화 표기 형태로 변환하기 황제낙엽 2008.07.08 348
141 NumberFormat, DecimalFormat 사용예 황제낙엽 2008.07.08 402
140 파일의 내용을 읽어 String 객체로 만드는 함수 황제낙엽 2008.06.17 296
139 UTF형태 파일에서 BOM 제거하기 황제낙엽 2008.06.16 2243
138 불러온 txt파일의 Encoding을 알 수는 방법좀 가르쳐 주세요~ 황제낙엽 2008.06.16 388
137 FileFilter, FilenameFilter 클래스를 이용한 파일 또는 디렉토리 리스트 추출하기 황제낙엽 2008.06.16 493
» 정규식 사용예제 [2] 황제낙엽 2008.06.11 384
135 정규식 사용예제 [1] 황제낙엽 2008.06.11 436
134 StringBuffer vs String 황제낙엽 2008.06.10 314
133 작지만 강력한 HTML 파서, HtmlCleaner, html parser 황제낙엽 2008.06.10 398
132 Jericho HTML Parser 황제낙엽 2008.06.10 556
131 JTidy(HTML Parser) How to 황제낙엽 2008.06.10 438
130 NekoHTML 샘플 예제 황제낙엽 2008.06.09 427
129 YGHTML Parser 0.1.1 샘플 예제 황제낙엽 2008.06.09 358
128 HTML Paser 의 종류 황제낙엽 2008.06.09 710
127 File 생성시 encoding 지정하기 (Unicode/utf-8 file 읽고 쓰기) 황제낙엽 2008.05.22 756
126 java String.replaceAll (String regex, String replacement) 쓸떄 조심할 것 황제낙엽 2008.05.22 424
125 java String.replaceAll 잘쓰기 황제낙엽 2008.05.22 429
124 간단한 DBConnection 프로그램 (JDBC) file 황제낙엽 2008.05.15 456