如何使用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[]) {
      //从用户读取字符串
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^\\w{5}";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

输出1

Enter a String
hello
Match occurred

输出2

Enter a String
#how
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 not occurred