java 删除正则表达式中的文字字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5314018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing literal character in regex
提问by Shervin Asgari
I have the following string
我有以下字符串
\Qpipe,name=office1\E
\Qpipe,name=office1\E
And I am using a simplified regex library that doesn't support the \Q
and \E
.
我正在使用一个不支持\Q
和的简化正则表达式库\E
。
I tried removing them
我尝试删除它们
s.replaceAll("\Q", "").replaceAll("\E", "")
However, I get the error Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1
\E
^
但是,我收到错误 Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1
\E
^
Any ideas?
有任何想法吗?
回答by codaddict
\
is the special escape character in both Java string and regex engine. To pass a literal \
to the regex engine you need to have \\\\
in the Java string. So try:
\
是 Java 字符串和正则表达式引擎中的特殊转义字符。要将文字传递\
给正则表达式引擎,您需要\\\\
在 Java 字符串中有。所以尝试:
s.replaceAll("\\Q", "").replaceAll("\\E", "")
Alternatively and a simpler way would be to use the replace
method which takes string and not regex:
或者,一种更简单的方法是使用replace
采用字符串而不是正则表达式的方法:
s.replace("\Q", "").replace("\E", "")
回答by desw
Use the Pattern.quote() function to escape special characters in regex for example
例如,使用 Pattern.quote() 函数来转义正则表达式中的特殊字符
s.replaceAll(Pattern.quote("\Q"), "")
回答by Mike Samuel
replaceAll
takes a regular expression string. Instead, just use replace
which takes a literal string. So myRegexString.replace("\\Q", "").replace("\\E", "")
.
replaceAll
采用正则表达式字符串。相反,只需使用replace
which 需要一个文字字符串。所以myRegexString.replace("\\Q", "").replace("\\E", "")
。
But that still leaves you with the problem of quoting special regex characters for your simplified regex library.
但这仍然会给您带来为简化的正则表达式库引用特殊正则表达式字符的问题。
回答by Bombe
String.replaceAll()takes a regular expression as parameter, so you need to escape your backslash twice:
String.replaceAll()将正则表达式作为参数,因此您需要将反斜杠转义两次:
s.replaceAll("\\Q", "").replaceAll("\\E", "");