如何使用 Java RegEx 匹配任何字符


java 正则表达式中的元字符“.”可以匹配任意(单个)字符,它可以是字母、数字或任何特殊字符。

示例 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();
      //Regular expression to match any character
      String regex = ".";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count ++;
      }
      System.out.println("Given string contains "+count+" characters.");
   }
}

输出

Enter a String
hello how are you welcome to tutorialspoint
Given string contains 42 characters.

你可以使用以下正则表达式匹配 a 和 b 之间任意 3 个字符 -

a…b

类似地,表达式“.*”匹配 n 个字符。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例 2

以下 Java 程序从用户读取 5 个字符串,并接受那些以 b 开头、以 a 结尾,并包含任意数量字符的字符串。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "^b.*a$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i]+": accepted");
         } else {
            System.out.println(input[i]+": not accepted");
         }
      }
   }
}

输出

Enter 5 input strings:
barbara
boolean
baroda
ram
raju
barbara: accepted
boolean: not accepted
baroda: accepted
ram: not accepted
raju: not accepted

更新于: 19-11-2019

847 次浏览

开启您的职业

完成课程并获得认证

开始
广告