Reputation: 32321
This is my program
package com.util;
public class SplitBy {
public static void main(String args[]) {
String name = "Masala Roasted with peanuts(49)";
String category_id = "";
if (!name.contains(",")) {
if (name.contains("(")) {
String[] parts = name.split("\\(");
category_id = parts[1];
System.out.println(category_id);
}
}
}
}
With this the current output is
49)
Please let me know how to get rmove the closing bracket and produce only
49
Upvotes: 1
Views: 188
Reputation: 355
Check this out
package com.util;
public class SplitBy {
public static void main(String args[]) {
String s = "";
Pattern pattern = Pattern.compile("(?<=)(\\d+)");
String EXAMPLE_TEST = "Masala Roasted with peanuts(49)";
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
while (matcher.find()) {
s = matcher.group(1);
}
System.out.println(s);
}
}
Upvotes: 0
Reputation: 11890
You can split the String
on both brackets:
String[] parts = name.split("[()]");
[()]
is a regular expression matching both the openning and closing brackets. As split()
is splitting the String
around matches, the closing bracket will not be included in the resulting value.
According to the split()
javadoc,
Trailing empty strings are therefore not included in the resulting array.
which means that it won't add an empty element at the end of your array.
Upvotes: 3
Reputation: 1184
You can look for both parentheses and only print the content in between:
category_id = name.substring(name.indexOf("(")+1, name.indexOf(")"));
Upvotes: 0
Reputation: 3313
You can do something like this:
category_id = category_id.substring(0, category_id.length() - 1);
Which will remove the last character from your String.
Upvotes: 2