Java 中如何使用正則表示式進行模式匹配?
正則表示式是一個字串,它定義/形成一個模式以搜尋輸入文字。正則表示式可以包含一個或多個字元,使用正則表示式,您可以搜尋或替換字串。
Java 提供了 java.util.regex 包,用於使用正則表示式進行模式匹配。該包的pattern 類是正則表示式的已編譯表示形式。要匹配正則表示式和字串,此類提供了兩種方法,即 -
- compile():此方法接受表示正則表示式的字串,並返回 Pattern 物件的物件。
- matcher(): 此方法接受字串值,並建立一個匹配物件,將給定的字串與當前模式物件表示的模式進行匹配。
示例
以下 Java 程式接受使用者輸入的字串,驗證它是否包含字母(大小寫),它還接受數字。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main( String args[] ) { String regex = "[a-zA-Z][0-9]?"; Scanner sc = new Scanner(System.in); System.out.println("Enter an input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern p = Pattern.compile(regex); //Creating a Matcher object Matcher m = p.matcher(input); if(m.find()) { System.out.println("Match occurred"); }else { System.out.println("Match not occurred"); } } }
輸出 1
Enter an input string: sample text Match occurred
輸出 2
Enter an input string: sample text 34 56 Match occurred
廣告