Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

java - 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);

But I get the exception

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 15 .(conflicted.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Escaping is done by . In Java, is written as \1, so you should escaping the ( would be \(.

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 Because a character preceded by a backslash () is an escape sequence and has special meaning to the compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...