正則表示式中的 Pattern.matches() 方法在 Java
java.util.regex.Pattern.matches() 方法匹配正則表示式和給定的輸入。它有兩個引數,即正則表示式和輸入。如果正則表示式和輸入匹配,則返回 true,否則返回 false。
一個演示 Java 正則表示式中 Pattern.matches() 方法的程式如下所示
示例
import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { String regex = "a*b"; String input = "aaab"; System.out.println("Regex: " + regex); System.out.println("Input: " + input); boolean match = Pattern.matches(regex, input); System.out.println("
Does the regex match with the input? " + match); } }
輸出
Regex: a*b Input: aaab Does the regex match with the input? true
現在讓我們來理解一下上面的程式。
列印正則表示式和輸入值。然後,Pattern.matches() 方法匹配正則表示式和給定的輸入,並列印結果。以下程式碼片段演示了這一點
String regex = "a*b"; String input = "aaab"; System.out.println("Regex: " + regex); System.out.println("Input: " + input); boolean match = Pattern.matches(regex, input); System.out.println("
Does the regex match with the input? " + match);
廣告