java의 java.util.regex 패키지는 문자 시퀀스에서 특정 패턴을 찾기 위한 다양한 클래스를 제공합니다. 이 패키지의 패턴 클래스는 정규 표현식의 컴파일된 표현입니다.
주어진 입력 문자열에서 특정 문자를 일치시키려면 -
-
입력 문자열을 가져옵니다.
-
이 컴파일() 이 클래스의 메서드는 정규식을 나타내는 문자열 값을 허용하고 플래그를 나타내는 정수 값은 Pattern 개체를 반환합니다. 정규식을 우회하여 컴파일 -
-
패턴 일치자 "[ ] "에 필수 문자 포함(예:"[t]").
-
대소문자를 무시하는 CASE_INSENSITIVE 플래그입니다.
-
-
매처() 패턴의 방법 클래스는 입력 문자열을 받아들이고 Matcher 객체를 반환합니다. 이 방법을 사용하여 매처 개체를 생성/검색합니다.
-
찾기() − find() 사용 Matcher의 메소드가 일치합니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "[t]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 출력
Enter input string Tutorialspoint Number of matches: 3