Reputation: 5137
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.
Upvotes: 95
Views: 274311
Reputation: 168853
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 -- [(]
Upvotes: 149
Reputation: 138147
(
with the pattern
\(
. Regex.Escape
or Java's Pattern.quote
\Q
and \E
, with literal text between them.(
literally, and require \(
for capturing groups.See also: Regular Expression Basic Syntax Reference
Upvotes: 7
Reputation: 993
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.
Upvotes: 9
Reputation: 25609
Because (
is special in regex, you should escape it \(
when matching. However, depending on what language you are using, you can easily match (
with string methods like index()
or other methods that enable you to find at what position the (
is in. Sometimes, there's no need to use regex.
Upvotes: 1
Reputation: 7951
For any special characters you should use '\'. So, for matching parentheses - /\(/
Upvotes: 3