English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Regex의 matchs()와 find()의 차이점은 무엇인가요?

java.util.regex.Matcher이 클래스는 일정한 엔진을 대표하고 다양한 매칭 작업을 수행합니다. 이 클래스는 생성자를 가지지 않으며,matches()java.util.regex.Pattern 클래스의 메서드를 생성/이 클래스의 객체를 얻습니다.

매칭()발견()Matcher 클래스의 메서드를 사용하여 입력 문자열에서 정규 표현식에 따라 일치를 찾으려고 시도합니다. 일치되면 두 메서드 모두 true를 반환하고, 일치되지 않으면 두 메서드 모두 false를 반환합니다.

주요 차이점은 이matches()이 메서드는 주어진 입력의 전체 区域을 매칭 시도합니다. 즉, 한 행에서 숫자를 검색하는 경우에만, 입력이 모든 행에서 숫자가 포함되어 있을 때 이 메서드는 true를 반환합니다.

예1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(.*)"(\\d+)".;*
      String input = "This is a sample Text, 1234, with numbers in between. "
         + "\n This is the second line in the text "
         + "\n This is third line in the text";
      //패턴 객체 생성
      Pattern pattern = Pattern.compile(regex);
      //Matcher 객체 생성
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         else {
      }
         System.out.println("일치하는 항목을 찾을 수 없습니다.");
      }
   }
}

출력 결과

일치 항목을 찾을 수 없습니다

그리고 이find()이 메서드는 패턴과 일치하는 다음 서브 문자열을 찾으려고 시도합니다. 즉, 해당 区域에서 최소한 하나의 일치 항목이 발견되면 이 메서드는 true를 반환합니다.

아래 예제를 보면, 특정 행과 중간의 숫자를 매칭 시도합니다.

예2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(.*)"(\\d+)".;*
      String input = "This is a sample Text, 1234, with numbers in between. "
         + "\n This is the second line in the text "
         + "\n This is third line in the text";
      //패턴 객체 생성
      Pattern pattern = Pattern.compile(regex);
      //Matcher 객체 생성
      Matcher matcher = pattern.matcher(input);
      //System.out.println("현재 범위: "+input.substring(regStart, regEnd));
      if(matcher.find()) {
         else {
      }
         System.out.println("일치하는 항목을 찾을 수 없습니다.");
      }
   }
}

출력 결과

일치하는 항목 찾기