Java中的模式類
Pattern類別表示正規表示式模式的編譯版本。 Pattern類別位於java.util.regex套件中。此類別具有各種方法,用於匹配、分割、搜尋等各種操作。為了建立一個模式對象,需要使用compile方法。
文法
public static Pattern compile(String regex)
這裡的regex代表一個正規表示式,它是一個字串。為了編譯它,我們使用這個方法。此外,這個編譯物件可用來使用 Matcher 方法來匹配模式。
演算法
要編譯並匹配模式,請按照以下步驟操作 -
第 1 步 - 使用字串初始化正規表示式模式。
第二步 - 現在,使用compile方法編譯模式。
第三步驟 - 定義要與模式相符的輸入字串。
第 4 步 - 建立一個 Matcher 物件並將模式套用到輸入字串。
第五步 − 使用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()方法來示範第二種方法。
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 |
#方法二 |
---|---|---|
#類型 |
字串 |
字串 |
方法 |
布林符合(字串正規表示式) |
布林查找() |
#方法邏輯 |
如果符合成功則回傳模式 |
返回符合模式 |
#結論
正規表示式用於匹配模式。上述方法是匹配模式時應採取的操作範例。我們還透過兩個工作範例演示了這些方法,展示了它們的功能和多功能性。透過了解這些方法及其用例,您可以使用正規表示式有效地找到匹配模式
以上是Java中的模式類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)
