Q 元字符在 Java 中的正则表达式
子表达式/元字符“\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("Enter input string: "); String input = sc.nextLine(); //Creating a Pattern object 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"); } } }
输出
Enter input string: 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("Enter input string: "); String input = sc.nextLine(); //Creating a Pattern object 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 input string: sample Match not occurred
输出 2
Enter input string: The letters [aeiou] are vowels in English alphabet Match occurred
广告