-1

I am trying to split a java string with the character "(".

For example :

split("wer(sde")= "wer"+"sde".

But it give exception. Is there a way to split this string using split() function without changing the character "(" to some other character.

String[] cp=cmd.split("{");

Output: Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Prakhar Gurawa
  • 373
  • 3
  • 13

3 Answers3

4

The thing is, split() receives as parameter a regular expression. Both {} and () are meta-characters and have a special meaning in a regex, so you need to escape them like this:

String[] cp = cmd.split("\\(|\\)");
Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

The method split of String accept a String, that parameter is a regex :

public String[] split(String regex)
Splits this string around matches of the given regular expression.

Since ( is a reserved character in regex, you need to escape it \(.
But in Java, you need to escape twice \\(, once for the String and the second for the regex

This gives :

s.split("\\(");
AxelH
  • 14,325
  • 2
  • 25
  • 55
1

Parentheses mean something in RegEx, they're used to group characters together. As such, if you intend to reference the literal character, '(' you must escape it within the RegEx:

String[] cp = cmd.split("\\(");

Note the use of two backslashes. This is because the JVM will also interpret a backslash as a metacharacter for escape purposes, so you must escape the backslash itself with another backslash in order for it to make it into the RegEx.

Alexander Guyer
  • 2,063
  • 1
  • 14
  • 20