Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for matching parentheses

Tags:

java

regex

What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

str = "abc(efg)";

I want to split the string at '(' using regular expression.For that i am using

Arrays.asList(Pattern.compile("/(").split(str))

But i am getting the following exception.

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

Escaping '(' doesn't seems to work.

like image 811
Ammu Avatar asked Apr 12 '11 10:04

Ammu


People also ask

How do you match a literal parenthesis in a regular expression?

The way we solve this problem—i.e., the way we match a literal open parenthesis '(' or close parenthesis ')' using a regular expression—is to put backslash-open parenthesis '\(' or backslash-close parenthesis '\)' in the RE. This is another example of an escape sequence.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


3 Answers

Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

like image 187
Spudley Avatar answered Oct 07 '22 17:10

Spudley


  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

like image 44
Kobi Avatar answered Oct 07 '22 17:10

Kobi


The solution consists in a regex pattern matching open and closing parenthesis

String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis, 
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
   // I print first "Your", in the second round trip "String"
   System.out.println(part);
}

Writing in Java 8's style, this can be solved in this way:

Arrays.asList("Your(String)".split("[\\(\\)]"))
    .forEach(System.out::println);

I hope it is clear.

like image 8
Fernando Aspiazu Avatar answered Oct 07 '22 17:10

Fernando Aspiazu