使用示例

String pattern = Pattern.quote("1252343% 8 567 hdfg gf^$545");
System.out.println("Pattern is : "+pattern);

输出结果为
Pattern is : \Q1252343% 8 567 hdfg gf^$545\E


方法解释

在使用quote()方法之后,原有的字符串s变成了\Qs\E的样式,那么\Q和\E代表什么意思呢?

  • \Q 代表字面内容的开始
  • \E 代表字面内容的结束

也就是说,调用Patter.quote()方法之后,原有的字符串被\Q..\E包裹,返回后的字符串成了正则字面量.举个例子,正则表达式”.*”表示匹配除“\n”之外的任何字符多次.

Pattern pattern = Pattern.compile(".*");
Matcher matcher = pattern.matcher("123");
boolean matches = matcher.matches();//true
System.out.println(matches);
matcher = pattern.matcher("foo");
matches = matcher.matches();//true
System.out.println(matches);

而使用quote()方法,可以把正则表达式”.*”转换为它的字面量,请看下例

String regex = Pattern.quote(".*");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("123");
boolean match = matcher.matches();// false
System.out.println(match);
matcher = pattern.matcher("foo");// false
System.out.println(match);
matcher = pattern.matcher(".*");
match = matcher.matches();// true
System.out.println(match);

通过上面例子就可以看出,当使用quote()方法后,将”.*”转换为了它的字面量意思,也就是只能匹配”.*”字符串.用API里面的一句话解释就是Metacharacters or escape sequences in the input sequence will be given no special meaning(使给定的正则表达式没有任何的特殊意义)

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐