String 데이터를 처리하기 위한 코딩을 할 때 알아두면 굉장히 도움 되는 것이 Regular Expression이다.

이게 뭔지도 모르신다면, 아래의 링크를 따라가서 한번 읽어 보시기를 권장한다.

http://java.sun.com/docs/books/tutorial/essential/regex/index.html

예를 들어 e-mail 주소나 URL의 정합성을 체크할 때 굉장히 편하게 사용할 수 있다.
Regular Expression을 주로 사용하는 언어들은 grep, Perl, Tcl, Python, PHP, awk 등이 있다.

Java 에서도 JDK 1.4 버젼부터 Regular Expression을 사용하기 시작했으며, java.util.regex.Pattern 클래스의 API 를 보면 Regular Expression에서 사용되는 패턴 구성을 볼 수 있다.

참고로,이미 만들어진 Regular Expression 들을 참조하고 싶다면, 아래의 사이트를 방문하기 바란다.
http://regexlib.com/

그럼 간단하게 Java를 이용해서 Regular Expression을 사용하는 방법에 대해서 알아보자.

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTester {

    public static void main(String[] args){
        RegexTester rt=new RegexTester();
        while(true) {
            rt.checkRegularExpression();
        }
    }
    public void checkRegularExpression() {       
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter Regular expression pattern : ");
        String regex=sc.nextLine();
        while(check(regex));
    }
    public boolean check(String regex) {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter data: ");
        String data=sc.nextLine();
            Pattern samplePattern = Pattern.compile(regex);
            Matcher matcher = samplePattern.matcher(data);
            boolean found = false;
            while (matcher.find()) {
                System.out.format("Text \"%s\" is found : from index %d - to index %d.\n",
                    matcher.group(), matcher.start(), matcher.end());
                found = true;
            }
            if(!found){
                System.out.format("No match found.\n");
            }
            System.out.print("Check another data ? [Y or y] or Quit [Q or q] : ");
            String another=sc.nextLine();
            if(another.equals("Q") || another.equals("q")) {
                System.exit(0);
                return false;
            } else if(another.equals("Y") || another.equals("y")) {
                return true;
            } else {
                return false;
            }
    }

}

이 프로그램은 Regular Expression을 입력하고, 문자열을 입력하면 입력된 문자열중 Regular Expression과 맞는 (match되는) 문자열이 어떤것이 있는지를 화면에 뿌려준다.

실행 결과 예는 다음과 같다.

Enter Regular expression pattern : [abc]
Enter data: abcdefg
Text "a" is found : from index 0 - to index 1.
Text "b" is found : from index 1 - to index 2.
Text "c" is found : from index 2 - to index 3.
Check another data ? [Y or y] or Quit [Q or q] : y
Enter data:
No match found.
Check another data ? [Y or y] or Quit [Q or q] : y
Enter data: cbfhgft
Text "c" is found : from index 0 - to index 1.
Text "b" is found : from index 1 - to index 2.
Check another data ? [Y or y] or Quit [Q or q] : q

다음 글에는 Regular Expression을 어떻게 지정하는지 알아보자.

Posted by tuning-java
,