逃脱(正则表达式 [英] Escape ( in regular expression
问题描述
我正在搜索正则表达式 - 。(冲突副本。。我为此写了以下代码
Im searching for the regular expression - ".(conflicted copy.". I wrote the following code for this
String str = "12B - (conflicted copy 2013-11-16-11-07-12)";
boolean matches = str.matches(".*(conflicted.*");
System.out.println(matches);
但我得到了异常
线程main中的异常java.util.regex.PatternSyntaxException:索引附近的未闭合组15
。(冲突。
我知道编译器认为(
是开头模式组。我试图通过添加 \(
)来逃避(
,但这不起作用。
I understand that the compiler thinks that (
is the beginning of a pattern group. I tried to escape (
by adding \(
but that doesnt work.
有人可以告诉我如何逃避(
这里?
Can someone tell me how to escape (
here ?
推荐答案
转义是由 \
完成的。在Java中, \
写成 \\
1 ,所以你应该逃避g (
将是 \\(
。
Escaping is done by \
. In Java, \
is written as \\
1, so you should escaping the (
would be \\(
.
旁注:最好看看 Pattern#quote
返回一个文字模式字符串。在你的情况下,它没有那么有用,因为你不想逃避所有特殊字符。
Side note: It's good to have a look at Pattern#quote
that returns a literal pattern String. In your case, it's not that helpful since you don't want to escape all special-characters.
1 因为前面带有反斜杠的字符( \
)是一个转义序列,并且具有特殊功能对编译器的意义。
1 Because a character preceded by a backslash (\
) is an escape sequence and has special meaning to the compiler.
这篇关于逃脱(正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!