티스토리 뷰

예제 코드는 모두 Java 언어를 사용한다.


텍스트 영역 내에 특정 위치에서 텍스트를 찾아야 할 때도 있다.

그러려면 위치 찾기가 필요하며, 이번에 배워볼 것이다.

경계 지정하기

위치 찾기는 텍스트 문자열 안에서 반드시 일치해야 하는 위치를 지정할 때 사용한다.

경계를 사용하거나 패턴 앞이나 뒤에 특정한 위치 혹은 경계를 나타내는 메타 문자를 사용하면 된다.

단어 경계 지정하기

가장 흔하게 쓰는 방법 중 하나로, \b로 표시하는 단어 경계이다.

단어 경계라는 이름에서 유추해 볼 수 있듯이, \b는 단어의 시작이나 마지막을 일치시킬 때 사용한다.

public class code {
    public static void main(String[] args) {
        String regex = "\\\\ba[0-9]{2}\\\\b";
        Pattern pattern = Pattern.compile(regex);

        String[] strs = {
                "a1",
                "a12",
                "a123",
                "1a"
        };

        int count = 1;
        for(String str : strs) {
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()) {
                System.out.println(count++ + ". : " + matcher.group());
            }
        }
    }
}
/*
1. : a12
*/

\b를 사용하면 이전에 a123까지 나왔던 상황은 피할 수 있다.

단어 경계와 일치시키고 싶지 않을 땐, \B를 사용한다.

문자열 경계 정의하기

단어 경계는 단어의 위치를 기반으로 위치를 찾는다.

문자열 경계는 단어 경계와 기능은 비슷하지만, 전체 문자열의 시작이나 마지막 부분과 패턴을 일치시키고자 할 때 사용한다.

문자열 경계는 메타 문자 가운데 캐럿(^)으로 문자열의 시작을, 달러 기호($)로 문자열의 마지막을 나타낸다.

다음 예시는 주어진 텍스트가 XML 문서인지 아닌지 간단하게 검사한다.

<?xml>로 시작하거나 <?xml ?>로 표현할 수 있다.

public class code {
    public static void main(String[] args) {
        String regex = "<\\\\?xml.*\\\\?>";
        Pattern pattern = Pattern.compile(regex);

        String[] strs = {
                "",
                "sadasdsad",
                "http://tips.cf>" ",="" "xmlns:impl="<http://tips.cf>" xmls:'intf="<a" href="http://tips.cf'">http://tips.cf'",
                "xmlns:apachesoap='<http://xml.apache.org/xml-soap>'"
        };

        int count = 1;
        for(String str : strs) {
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()) {
                System.out.println(count++ + ". : " + matcher.group());
            }
        }
    }
}
/*
1. : 
2. : 
*/

XML을 여는 태그가 문자열 안에 있는 실제 텍스트에서 첫 번째 줄에 위치한다는 사실을 확인해야 한다.

이 작업을 위해 캐럿(^) 메타 문자가 제격이다.

public class code {
    public static void main(String[] args) {
        String regex = "^\\\\s*<\\\\?xml.*\\\\?>";
        Pattern pattern = Pattern.compile(regex);

        String[] strs = {
                "",
                "sadasdsad",
                "http://tips.cf>" ",="" "xmlns:impl="<http://tips.cf>" xmls:'intf="<a" href="http://tips.cf'">http://tips.cf'",
                "xmlns:apachesoap='<http://xml.apache.org/xml-soap>'"
        };

        int count = 1;
        for(String str : strs) {
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()) {
                System.out.println(count++ + ". : " + matcher.group());
            }
        }
    }
}
/*
1. : 
*/

달러 기호($)도 캐럿(^) 문자와 매우 유사한 방법으로 사용한다.

다음 패턴은 웹 페이지에서 닫는 </html> 태그 뒤에 아무 문자도 나오지 않는지 확인하는 데 사용한다.

public class code {
    public static void main(String[] args) {
        String regex = "</[Hh][Tt][Mm][Ll]>\\\\s*$";
        Pattern pattern = Pattern.compile(regex);

        String[] strs = {
                "<HTML>eric test</HTML>",
                "<HTML>eric test</HTML>eric test"
        };

        int count = 1;
        for(String str : strs) {
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()) {
                System.out.println(count++ + ". : " + matcher.group());
            }
        }
    }
}
/*
1. : </HTML>
*/
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함