java.util.regex.Matcher 클래스는 다양한 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스에 대한 생성자가 없습니다. java.util.regex.Pattern 클래스의 match() 메소드를 사용하여 이 클래스의 객체를 생성/얻을 수 있습니다.
보고() 매처 메소드 클래스는 영역의 시작 부분에서 시작하여 주어진 입력 텍스트를 패턴과 일치시킵니다. 일치하는 경우 이 메서드는 true, 그렇지 않으면 false를 반환합니다. match() 메서드와 달리 이 메서드는 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";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//checking for the match
if(matcher.lookingAt()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} 출력
Match found
예시 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LookingAtExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String1: ");
String input1 = sc.nextLine();
System.out.println("Enter String2: ");
String input2 = sc.nextLine();
System.out.println("Enter String3: ");
String input3 = sc.nextLine();
String input = input1+"\n"+input2+"\n"+input3;
System.out.println(input);
//Regular expression to match a word that contain digits
String regex = ".*\\d+.*";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//verifying whether match occurred
boolean bool = matcher.lookingAt();
if(bool) {
System.out.println("Given input contains digit");
} else {
System.out.println("Given input does not contain any digit");
}
}
} 출력
Enter String1: sample text2 Enter String2: data Enter String3: sample sample text2 data sample Given input contains digit