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”。