Java中的Pattern類
Pattern 類表示正則表示式模式的編譯版本。Pattern 類位於 java.util.regex 包中。此類包含用於各種操作(如匹配、分割、搜尋等)的各種方法。為了建立一個 Pattern 物件,可以使用 compile 方法。
語法
public static Pattern compile(String regex)
這裡 regex 表示一個正則表示式,它是一個字串。為了編譯它,我們使用此方法。此外,此編譯後的物件可用於使用 Matcher 方法匹配模式。
演算法
要編譯並匹配模式,請按照以下步驟操作:
步驟 1 - 使用字串初始化正則表示式模式。
步驟 2 - 現在,使用 compile 方法編譯模式。
步驟 3 - 定義要與模式匹配的輸入字串。
步驟 4 - 建立一個 Matcher 物件並將模式應用於輸入字串。
步驟 5 - 使用 Matcher 方法執行各種操作
語法
public class Regex {
public static void main(String[] args) {
String pattern = "String1";
Pattern compiledPattern = Pattern.compile(pattern);
String input = "Strin2";
Matcher matcher = compiledPattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found: " + matcher.group(0));
System.out.println("Captured group: " + matcher.group(1));
} else {
System.out.println("No match found.");
}
}
}
方法 1:使用 matches() 方法
此方法涉及使用 matches() 方法。
示例
import java.util.regex.Pattern;
public class MatchThePattern {
public static void main(String[] args) {
String pattern = "Hello (\w+)";
String input = "Hello World"; // Add the input string to be matched
boolean letsMatch = Pattern.matches(pattern, input);
if (letsMatch) {
System.out.println("Pattern matched.");
} else {
System.out.println("Pattern not matched.");
}
}
}
輸出
Pattern matched.
解釋
透過將兩個字串輸入作為引數傳遞給 matches 方法,我們可以成功匹配上述程式碼中的兩個字串模式。
方法 2:使用 find() 方法
find() 方法返回布林型別並查詢與模式匹配的表示式。以下是一個程式碼示例:
示例
在此示例中,我們將透過使用 find() 方法演示方法 2。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LetsFindPattern {
public static void main(String[] args) {
String pattern = "\b\d+\b";
String input = "The price is 100 dollars for 3 items.";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
while (matcher.find()) {
System.out.println("Match found: " + matcher.group());
}
}
}
輸出
Match found: 100 Match found: 3
方法 1 和方法 2 的比較
標準 |
方法 1 |
方法 2 |
|---|---|---|
型別 |
字串 |
字串 |
方法 |
boolean matches(String regex) |
boolean find() |
方法邏輯 |
如果匹配則返回模式 |
返回匹配的模式 |
結論
正則表示式用於匹配模式。上述方法是應該採取以匹配模式的操作示例。我們還透過兩個有效的示例演示了這些方法,展示了它們的功能和多功能性。透過理解這些方法及其用例,您可以有效地使用正則表示式查詢匹配的模式。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP