在 Java 中使用 Pattern 類進行匹配
正則表示式的表示方式可在 java.util.regex.Pattern 類中找到。此類基本上定義了正則引擎所使用的模式。
以下是一個演示在 Java 中使用 Pattern 類進行匹配的程式 −
示例
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("p+"); Matcher m = p.matcher("apples and peaches are tasty"); System.out.println("The input string is: apples and peaches are tasty"); System.out.println("The Regex is: p+ "); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); } } }
輸出
The input string is: apples and peaches are tasty The Regex is: p+ Match: pp Match: p
現在,我們來理解一下上面的程式。
在字串序列"apples and peaches are tasty"中搜索子序列“p+”。Pattern 類定義了正則引擎所使用的模式,即“p+”。find() 方法用於查詢子序列,即 p 後跟任意數量的 p 是否在輸入序列中,並列印所需結果。下面是一個演示此過程的程式碼片段 −
Pattern p = Pattern.compile("p+"); Matcher m = p.matcher("apples and peaches are tasty"); System.out.println("The input string is: apples and peaches are tasty"); System.out.println("The Regex is: p+ "); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); }
廣告