共計 912 個字符,預計需要花費 3 分鐘才能閱讀完成。
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”。
丸趣 TV 網 – 提供最優質的資源集合!
正文完