Java 中的正则表达式 Q 元字符

javaobject oriented programmingprogramming更新于 2025/7/13 11:24:17

子表达式/元字符"\Q"转义所有字符直到"\E",即,您可以通过将正则表达式中的元字符放在 \Q 和 \E 之间来转义它们。例如,表达式 [aeiou] 匹配其中包含元音字母的字符串。

示例 

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入字符串: ");
      String input = sc.nextLine();
      //创建一个 Pattern 对象
      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");
      }
   }
}

输出

输入输入字符串:
sample
Match occurred

但是,如果您在 \Q 和 \E 中使用与 \Q[aeiou]\E 相同的表达式,它将与给定字符串中的相同字符序列"[aeiou]"匹配。简而言之,元字符将失去其含义并将被视为普通字符

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "\Q[aeiou]\E";
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入字符串: ");
      String input = sc.nextLine();
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
          System.out.println("匹配发生");
      } else {
          System.out.println("匹配未发生");
      }
   }
}

输出 1

输入输入字符串:
sample
匹配未发生

输出 2

输入输入字符串:
The letters [aeiou] are vowels in English alphabet
匹配发生

相关文章


有用资源