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

황제낙엽 2008.06.11 13:54 조회 수 : 75 추천: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());
   }
}