ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 47일차 - 정규표현식
    프로그래밍 언어/자바(JAVA) 2024. 3. 29. 16:43
    String str = "01038919755";// 이 문자열에서 "0" 만 찾아볼것이다
    
    // 1. 패턴을 정의한다
    Pattern p = Pattern.compile("0");
    // 2. 패턴에 대해서 찾아달라고 요청한다
    // 특정 패턴을 어느 문자열에 대입해서 찾을 것인가?
    Matcher m = p.matcher(str);
    // 3. 찾은 내용을 확인한다
    while(m.find()) {
        // group : 요청 패턴 그룹으로 찾은 내용을 반환한다
        // start : 찾은 문자열의 시작 위치를 반환한다
        // end : 찾은 문자열의 마지막 위치를 반환한다
        System.out.println(m.group() +  " : " + m.start() + "~" + m.end());
    Pattern p = null;
    Matcher m = null;
    boolean result;
    
    // ^x : x 로 시작하는..(문자열의 시작)
    p = Pattern.compile("^x");
    m= p.matcher("xlist");
    result = m.find();
    // 메서드 체이닝
    result = p.matcher("xlist").find();
    /*
     * System.out.println("xlist : " + result); System.out.println("listx : " +
     * p.matcher("listx").find()); System.out.println("myxlist : " +
     * p.matcher("myxlist").find());
     */
    
    
    // x$ : x 로 끝나는.. (문자열의 종료)
    /*
     * p = Pattern.compile("x$"); System.out.println("listx : " +
     * p.matcher("listx").find()); System.out.println("myxlist : " +
     * p.matcher("myxlist").find()); System.out.println("xlist : " +
     * p.matcher("xlist").find());
     */
    
    
    // x* : x가 있을수도 있지만 없을수도 있고 반복될수도 있다 
    // java 를 찾고 싶은데  java[s], java[v], java[a], java[] -> 자바 로 바꾸고 싶다
    // 무언가 잘못된 단어, 문장을 바꿀때 유용하다
    /*
     * p = Pattern.compile("x*"); System.out.println("y : " +
     * p.matcher("y").find()); System.out.println("x : " + p.matcher("x").find());
     * System.out.println("xxx : " + p.matcher("xxx").find());
     * System.out.println("myxlist : " + p.matcher("myxlist").find());
     */
    
    // x? : x 가 있을수도 있지만 없을 수도 있다
    /*
     * p = Pattern.compile("x?y"); System.out.println("xy : " +
     * p.matcher("xx").find()); // true System.out.println("y : " +
     * p.matcher("y").find()); System.out.println("x : " + p.matcher("x").find());
     */ 
    
    // x|y : x 또는 y 가 존재한다
    /*
     * p = Pattern.compile("two|three"); m = p.matcher("two or three"); while
     * (m.find()) { // index 값을 이용해서 subString 등에 활용할 수 있다
     * System.out.println(m.group() + " : " + m.start() + "~" + m.end()); }
     */
    
    // x.y : x 와 y 사이에 임의의 한 문자가 올 수 있다
    p = Pattern.compile("x.y");
    System.out.println("xzy : " + p.matcher("xzy").find());
    System.out.println("xy : " + p.matcher("xy").find());
    System.out.println("x0y : " + p.matcher("x0y").find());
    System.out.println("xaay : " + p.matcher("xaay").find());
    public static void main(String[] args) {
        Pattern p = null;
        p = Pattern.compile("[to]");
    
        // [xy] : x|y 와 같다
        print("[to] t-world", p.matcher("t-world"));
    
        // [^xy] : x 와 y를 제외하고 
        p = Pattern.compile("[^cd]"); // c 와 d 를 제외하고
        print("[^cd] abcdefg", p.matcher("abcdefg"));
    
        // [a-z] : a 부터 z 까지
        p = Pattern.compile("[a-z]");
        print("[a-z] 123abc456", p.matcher("123abc456"));
    
        //[0-9] : 0 부터 9까지
        p = Pattern.compile("[0-9]");
        print("[0-9] 123abc456", p.matcher("123abc456"));
    
        // 특수 표현
        // \d : 숫자[0-9] 대신 사용
        p = Pattern.compile("[\\d]");
        print("[\\d] 123abc456", p.matcher("123abc456"));
    
        // \w : 알파벳 또는 숫자 또는 _ 하나의 문자
        p = Pattern.compile("[\\w]");
        print("[\\w] zer0-box_mail@naver.com", p.matcher("zer0-box_mail@naver.com"));
    
        // \b : 공백
        p = Pattern.compile("[[s]\b]");
        print("[[s]\\b] words characters, styles. lists!", p.matcher("words characters, styles. lists!"));
    
        // \s : 공백 사이 문자 
        p = Pattern.compile("[[s]\s]");
        print("[[s]\\s] words characters, styles. lists!", p.matcher("words characters, styles. lists!"));
    }
    
    public static void print(String target, Matcher m) {
        System.out.print(target + ":");
        while(m.find()) {
            System.out.print(m.group() + " ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Pattern p = null;
    
        // 다음중 문자가 섞인 값의 인덱스를 찾으시오
        System.out.println("============");
        String[] test1 = {"123", "1d2", "456", "ddd4", "132.456", "3@2"};
        p = Pattern.compile("[^0-9]");
        print(test1, p);
    
        // 다음중 특수문자가 사용된 값의 인덱스를 찾으시오
        String[] test2 = {"tester", "test!!", "master.id", "main_id"};
        p = Pattern.compile("[^\\w]");
        print(test2, p);
    }
    
    public static void print(String[] target, Pattern p) {
        Matcher m = null;
        boolean flag = false;
        int index = 0;
        for (String t : target) {
            flag = false;
            System.out.print(index++ + "  :  " + t + ":");
            m = p.matcher(t);
            while(m.find()) {
                System.out.print("{" + m.start() + ":" + m.group() +"}");
                flag = true;
            }
            if (flag) {
                System.out.println(" --- O");
            } else {
                System.out.println(" --- X");
            }
        }
        System.out.println("============");
    }
    public static void main(String[] args) {
        Pattern p = null;
        Matcher m = null;
        boolean result;
    
        System.out.println("(x) : x 를 그룹으로 처리함");
        p = Pattern.compile("(6CD)");
        print("(6CD) ab6CDE443fgh22iJKlmn1o", p.matcher("ab6CDE443fgh22iJKlmn1o"), 1);
    
        System.out.println("(x)(y) : x 와 y 는 다른 그룹으로 처리함");
        p = Pattern.compile("(6CD)|(443f)"); // 6CD 와 443f  를 둘 다 찾겠다
        print("(6CD)|(443f) ab6CDE443fgh22iJKlmn1o", p.matcher("ab6CDE443fgh22iJKlmn1o"), 1);
        print("(6CD)|(443f) ab6CDE443fgh22iJKlmn1o", p.matcher("ab6CDE443fgh22iJKlmn1o"), 2);
    
        // 시작시 공백이 없어도 첫문장이면 가져와준다(단어의 시작과 끝을 찾아내는대 유용하다)
        // 첫 시작 문자 두글자를 동시에 가져올 경우
        System.out.println("(x)(y) : x 와 y 는 다른 그룹으로 처리함");
        p = Pattern.compile("\\b([\\w])([\\w])"); // 6CD 와 443f  를 둘 다 찾겠다
        print("\\\\b([\\\\w])([\\\\w]) my team has groups", p.matcher("my team has groups"), 2);
    
        System.out.println("x(?!y) : x 다음에 y 가 오지 않는다");
        // 숫자 다음에 문자가 오지 않도록
        p = Pattern.compile("[0-9](?![a-zA-Z])");
        // ?! : 뒤에 있는 패턴을 포함하지 않아야한다 (부정형 전방 탐색)
        System.out.println("1234 : " + p.matcher("1234").find());
        System.out.println("1f : " + p.matcher("1f").find());
        System.out.println("1F : " + p.matcher("1F").find());
        // 1234
        // 1f
        // 1F
    
    }
    
    public static void print(String msg, Matcher m, int cnt) {
        System.out.print(msg + " : ");
        while(m.find()) {
            if (cnt > 1) {
                System.out.print(m.group(1) + ", " + m.group(2) + " / ");
            } else {
                System.out.print(m.group() + " ");
            }
        }
        System.out.println();
    }

     

Designed by Tistory.