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

javaobject oriented programmingprogramming更新于 2024/5/5 3:56:17

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[]) {
      //从用户处读取字符串
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //匹配任意字符的正则表达式
      String regex = ".";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count ++;
      }
      System.out.println("给定字符串包含 "+count+" 个字符。");
   }
}

输出

输入一个字符串
hello how are you welcome to tutorialspoint
给定字符串包含 42 个字符。

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

a…b

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

示例 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("请输入5个字符串: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //创建一个 Pattern 对象
      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");
         }
      }
   }
}

输出

请输入5个字符串:
barbara
boolean
baroda
ram
raju
barbara: accepted
boolean: not accepted
baroda: accepted
ram: not accepted
raju: not accepted

相关文章


有用资源