Pattern.quote方法有什么用? [英] What is the use of Pattern.quote method?
问题描述
我正在尝试使用以下代码了解 Pattern.quote
:
I'm trying to understand Pattern.quote
using the following code:
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
\ Q
和 \ E
这里有什么?文档描述说:
What are \Q
and \E
here? The documentation description says :
返回指定<$的文字模式
String
c $ c>字符串。
Returns a literal pattern
String
for the specifiedString
.
此方法生成可以使用的 String
创建一个 Pattern
,它将匹配字符串 s
,就好像它是一个文字模式。
This method produces a String
that can be used to create a Pattern
that would match the string s
as if it were a literal pattern.
输入序列中的元字符或转义序列没有特殊含义。
Metacharacters or escape sequences in the input sequence will be given no special meaning.
但是 Pattern.quote
的返回类型是 String
而不是已编译的模式
对象。
But Pattern.quote
's return type is String
and not a compiled Pattern
object.
为什么需要这种方法以及一些用法示例?
Why is this method required and what are some usage examples?
推荐答案
\ Q
表示文字文本的开头(即正则表达式公开引用)
\ E
表示文字结尾(即正则表达式关闭引用)
\Q
means "start of literal text" (i.e. regex "open quote")
\E
means "end of literal text" (i.e. regex "close quote")
调用 Pattern.quote()
方法将字符串包装在 \Q ... \ E
中,这会将文本转换为正则表达式 literal 。例如, Pattern.quote(。*)
将匹配一个点,然后是一个星号:
Calling the Pattern.quote()
method wraps the string in \Q...\E
, which turns the text is into a regex literal. For example, Pattern.quote(".*")
would match a dot and then an asterisk:
System.out.println("foo".matches(".*")); // true
System.out.println("foo".matches(Pattern.quote(".*"))); // false
System.out.println(".*".matches(Pattern.quote(".*"))); // true
该方法的目的是不要求程序员必须记住特殊条款 \Q
和 \ E
并为代码添加一点可读性 - 正则表达式已经很难阅读了。比较:
The method's purpose is to not require the programmer to have to remember the special terms \Q
and \E
and to add a bit of readability to the code - regex is hard enough to read already. Compare:
someString.matches(Pattern.quote(someLiteral));
someString.matches("\\Q" + someLiteral + "\\E"));
参考 javadoc :
返回指定String的文字模式String。
Returns a literal pattern String for the specified String.
此方法生成一个String,可用于创建一个与字符串s匹配的Pattern,就像它是一个文字模式一样。
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
输入序列中的元字符或转义序列没有特殊含义。
Metacharacters or escape sequences in the input sequence will be given no special meaning.
这篇关于Pattern.quote方法有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!