Reputation: 135
I have a String
like
Move Selected Patients (38)
I want to retrieve 38
between the parenthesis using java split.
Tried with this code:
String a1 = "Move Selected Patients (38)";
String[] myStringArray = new String[2];
myStringArray = a1.split("(", 2);
System.out.println(myStringArray[0]);
and it fails with this exception:
java.util.regex.PatternSyntaxException: Unclosed group near index 1.
Can anyone please help me out.
Upvotes: 1
Views: 377
Reputation: 191749
You need to escape the paren as the split argument is still a regular expression: \\(
. Keep in mind that this will still return 38)
as the second element. It would make more sense to use Matcher
to capture the contents of the parentheses in a group: \\((.*?)\\)
Upvotes: 5
Reputation: 8012
You can easily achieve the requirement with regex as shown below:
String str = "Move Selected Patients (38)";
Pattern pattern = Pattern.compile("\\((\\d+)\\)");
Matcher match = pattern.matcher(str);
while(match.find()) {
System.out.println(match.group(1));
}
Upvotes: 2
Reputation: 5609
Pattern p = Pattern.compile(".*\\(([0-9]*)\\)");
Matcher m = p.matcher("Move Selected Patients (38)");
String s = m.group(1);
If you need another part of the string as well, just use another group for it.
Upvotes: 2
Reputation: 51030
(
is regex metacharacter, you have to escape it using \\
. Try with \\(
.
Upvotes: 1