Pattern类是Java中用于创建正则表达式模式的类。下面是Pattern类的一些常用方法:
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("12345");
boolean result = matcher.matches();
boolean result = matcher.find();
String result = matcher.group();
int start = matcher.start();
int end = matcher.end();
下面是一个示例,演示如何使用Pattern类进行正则表达式匹配:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String input = "Hello, 12345";
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String result = matcher.group();
System.out.println("Found: " + result);
} else {
System.out.println("No match found.");
}
}
}
运行上述代码,输出为:
Found: 12345
这说明在输入字符串中找到了匹配正则表达式的子序列 “12345”。