子表达式/元字符“ \ E ”以\ Q开头的引用结束。即,您可以通过将它们放在\ 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