Java 中的 Pattern matcher() 方法示例

javaobject oriented programmingprogramming更新于 2024/5/7 0:44:17

Java 的 java.util.regex 包提供了各种类来查找字符序列中的特定模式。

此包的 pattern 类是正则表达式的编译表示。此类的 ma​​tcher() 方法接受表示输入字符串的 CharSequence 类的对象,并返回 Matcher 对象,该对象将给定的字符串与当前 (Pattern) 对象所表示的正则表达式进行匹配。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
   public static void main(String args[]) {
      //读取字符串值
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入字符串");
      String input = sc.nextLine();
      //用于查找元音的正则表达式
      String regex = "[aeiou]";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("给定字符串包含元音");
      } else {
         System.out.println("给定字符串不包含元音");
      }
   }
}

输出

输入输入字符串
RHYTHM
给定的字符串不包含元音

相关文章


有用资源