如何利用 Java RegEx 匹配非單詞字元?


除英語字母(大寫和小寫)和數字(0 到 9)之外的所有字元都被視為非單詞字元。可以使用元字元“\W”進行匹配。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^\W{5}";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

輸出 1

Enter a String
*&&^#
Match occurred

輸出 2

Enter a String
hello
Match not occurred

示例 2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\W*";
      System.out.println("Enter input value: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean bool = input.matches(regex);
      if(bool) {
         System.out.println("match occurred");
      } else {
         System.out.println("match not occurred");
      }
   }
}

輸出

Enter input value:
#***
match occurred

更新時間: 2019 年 11 月 19 日

1000+ 次瀏覽

開啟你的 職業生涯

透過完成此課程來獲取認證

開始學習
廣告
© . All rights reserved.