问题描述
在正则表达式处理期间,似乎拒绝包含字符 {
或}
的字符串。我可以理解这些是保留字符,如果我这样做,我需要逃避它们:
It seems that having a string that contains the characters {
or }
is rejected during regex processing. I can understand that these are reserved characters and I need to escape them so if I do:
string.replaceAll("\\" + pattern);
这是有效的,其中模式
是任何字符串从 {
开始。
This works, where pattern
is any string starting with {
.
问题:有没有办法避免此类问题已经包含此类metachars的字符串,以便自动处理?在我看来它应该与在字符串文字中添加双引号相比,接受字符串作为已经具有双引号的输入
Question: Is there a way to avoid such problems with strings that already contain such metachars so that it is handled automatically? Seems to me it should be the same as adding a double quote in a string literal vs accepting a string as input that already has the double quote
推荐答案
使用:
public static String quote(String s)
返回文字模式字符串
表示指定的字符串
。
Returns a literal pattern String
for the specified String
.
此方法产生 String
,可用于创建一个模式
,它将匹配字符串 s
as如果它是一个文字模式。
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.
参数:
s
- 要字面化的字符串
返回:
文字字符串替换
自:
1.5
Parameters:
s
- The string to be literalized
Returns:
A literal string replacement
Since:
1.5
这篇关于我是否总是需要在不是“文字”的字符串中转义元字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!