Java의 Matcher를 활용한 정규식 검색 및 추출

Java에서는 정규식 패턴 확인 및 추출을 위해 Matcher class의 find()나 matches() 메소드를 사용하게 된다. find()는 하나의 문자열 안에 여러 개의 정규식 패턴을 찾을 때 사용하며, matches()는 하나의 문자열과 하나의 정규식 표현이 일치하는지를 확인할 때 사용한다. 

find() 메소드

Matcher.find()는 하나의 문자에 여러 개의 정규식 패턴을 찾을 때 사용한다. 주어진 문자열에 정규식에 해당하는 n개의 패턴이 있다면 find()를 n번째 호출할 때까지는 true가 반환되며 이후 false가 반환된다. find()가 true일때는 start(), group(), end()메소드를 호출할 수 있다.

start는 문자열 내에서 정규식 패턴이 발견된 문자열의 시작 index, end는 끝 index를 의미한다. gruop은 정규식 패턴에 해당하는 문자열 자체를 반환한다.

Pattern stringPattern = Pattern.compile("[a-zA-Z]+");
Matcher m = stringPattern.matcher("hello there how are you");
while (m.find()) {
    int start = m.start();
    String group = m.group();
    int end = m.end();
    System.out.println("position [%d, %d] = %s".formatted(start, end, group));
}

위 코드를 실행하면 다음과 같이 출력된다.

position [0, 5] = hello
position [6, 11] = there
position [12, 15] = how
position [16, 19] = are
position [20, 23] = you

find(int start)

find를 호출할 때 int start라는 인자를 지정하면 해당 인덱스로부터 정규식 문자열을 검색하게 된다.

matches()

find()가 부분 패턴을 찾는 것과 달리, matches는 주어진 문자열 전체에 대해 정규식 패턴이 일치하는지를 확인한다.

Pattern stringPattern = Pattern.compile("[a-zA-Z]+");
Matcher m = stringPattern.matcher("hello there how are you");
System.out.println(m.matches());

위 코드를 실행하면 false가 출력된다. 그 이유는 문자열 중간에 공백이 들어있기 때문이다.

Pattern stringPattern = Pattern.compile("[a-zA-Z ]+");
Matcher m = stringPattern.matcher("hello there how are you");
boolean matched = m.matches();
System.out.println(matched);

위와 같이 정규식에 공백을 포함시키면 true가 반환된다.

Patterne.matches(String regex, CharSequence input)

Pattern의 static method인 matches()는 첫 번째 인자인 regex가 두 번째 인자인 input 문자열에 일치하는지 여부를 반환한다.

댓글

이 블로그의 인기 게시물

Java Gradle Project에서 Unit Test코드 작성하기

Java8 Stream API