Pattern类是Java中用于创建正则表达式模式的类。下面是Pattern类的一些常用方法:
- compile(String regex):将给定的正则表达式编译成Pattern对象。
Pattern pattern = Pattern.compile("[0-9]+");
- matcher(CharSequence input):创建一个Matcher对象,用于对输入字符串进行匹配。
Matcher matcher = pattern.matcher("12345");
- matches():尝试将整个输入序列与模式进行匹配。
boolean result = matcher.matches();
- find():尝试在输入序列中查找下一个匹配的子序列。
boolean result = matcher.find();
- group():返回上一个匹配操作的匹配结果。
String result = matcher.group();
- start():返回上一个匹配操作的匹配结果的起始位置。
int start = matcher.start();
- end():返回上一个匹配操作的匹配结果的结束位置。
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”。