Java 中的模式 compile() 方法,附带示例
java.regex 包的模式类是正则表达式的编译表示。
此类的 compile() 方法接受表示正则表达式的字符串值,并返回一个模式对象。
示例
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 = "(\d)";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Printing the regular expression
System.out.println("Compiled regular expression: "+pattern.toString());
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//verifying whether match occurred
if(matcher.find()) {
System.out.println("Given String contains digits");
} else {
System.out.println("Given String does not contain digits");
}
}
}输出
Enter input string hello my id is 1120KKA Compiled regular expression: (\d) Given String contains digits
此方法有另一个变体,它接受表示标志的整数值,其中每个标志指定一个可选条件,例如,CASE_INSENSITIVE 在编译正则表达式时会忽略大小写。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
public static void main( String args[] ) {
//Compiling the regular expression
Pattern pattern = Pattern.compile("[t]", Pattern.CASE_INSENSITIVE);
//Retrieving the matcher object
Matcher matcher = pattern.matcher("Tutorialspoint");
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}输出
Enter input string Tutorialspoint Number of matches: 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP