Java 中 Pattern 的 pattern() 方法与示例
Java 的 java.util.regex 套件提供多種類別用於在字串序列中找出特定樣式。此套件的 Pattern 類別為正規表達式的編譯表示。
Pattern 類別的 pattern() 方法使用編譯目前樣式的字串格式擷取和傳回正規表達式。
範例 1
import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { String date = "12/09/2019"; String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(date).matches()) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } }
輸出
Date is valid Regular expression: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
範例 2
public class PatternExample { public static void main(String[] args) { String input = "Hi my id is 056E1563"; //Regular expression using groups String regex = "(.*)?(\d+)"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(input).matches()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } }
輸出
Match found Regular expression: (.*)?(\d+)
广告