Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape ( in regular expression

Tags:

java

regex

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 ?

like image 604
Poornima Prakash Avatar asked Mar 17 '26 16:03

Poornima Prakash


2 Answers

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.

like image 120
Maroun Avatar answered Mar 20 '26 06:03

Maroun


( in regex is metacharacter which means "start of group" and it needs to be closed with ). If you want refex engine to tread it as simple literal you need to escape it. You can do it by adding \ before it, but since \ is also metacharacter in String (used for example to create characters like "\n", "\t") you need to escape it as well which will look like "\\". So try

str.matches(".*\\(conflicted.*"); 

Other option is to use character class to escape ( like

str.matches(".*[(]conflicted.*"); 

You can also use Pattern.quote() on part that needs to be escaped like

str.matches(".*"+Pattern.quote("(")+"conflicted.*"); 

Or simply surround part in which all characters should be threaded as literals with "\\Q" and "\\E" which represents start and end of quotation.

str.matches(".*\\Q(\\Econflicted.*"); 
like image 20
Pshemo Avatar answered Mar 20 '26 07:03

Pshemo