패턴 클래스의 컴파일 메소드는 두 개의 매개변수를 받습니다 -
- 정규 표현식을 나타내는 문자열 값입니다.
- Pattern 클래스의 정수 값 필드입니다.
Pattern 클래스의 이 CASE_INSENSITIVE 필드는 대소문자에 관계없이 문자와 일치합니다. 따라서 정규 표현식과 함께 compile() 메소드에 플래그 값으로 전달하면 두 경우의 문자가 일치합니다.
예시 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data: ");
String input = sc.nextLine();
//Regular expression to find the required character
String regex = "test";
//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 occurrences: "+count);
}
} 출력
Enter input data: test TEST Test sample data Number of occurrences: 3
예시 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
} 출력
Enter a string value: TRUE Given string is a boolean type