子表达式/元字符“ \ 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(); //创建一个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"); } } }
输出结果
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(); //创建一个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"); } } }
Enter input string: sample Match not occurred
Enter input string: The letters [aeiou] are vowels in English alphabet Match occurred