Junaid Junaid - 4 months ago 10
Java Question

string.parse("(") error

I have one file which contains data like following

recv(1178884, NULL, 4294967267, 0) = 0
......
......


My source code is:

try (BufferedReader br = new BufferedReader(new FileReader("D:\\smsTrace.txt")))
{
String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
String sysCallName = sCurrentLine;
String[] sysCallTokens = sysCallName.split("(");
System.out.println(sCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
}


When I split with
sysCallName.split(",")
, it works fine but when I use as above, it throws following exception.

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
(
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.accept(Unknown Source)
at java.util.regex.Pattern.group0(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.split(Unknown Source)
at java.lang.String.split(Unknown Source)
at fileReading.main(fileReading.java:19)


Any idea what I am doing wrong?

Answer

You have to escape the opening bracket:

sysCallName.split("\\(");

Because split() expects a regular expression, and brackets are used to mark capturing groups in a regex. So they need to be in pairs. If you just want a bracket it needs to be escaped.