[编辑]我不会使用正则表达式来解决这个问题;相反,我会简单地使用该String#lastIndexOf(...)
方法来查找最后一个字符的边界(
并)
从这些值返回子字符串:
public static String[] splitParens(String s) {
if (s == null) return null;
int indexOfLastOpenParen = s.lastIndexOf('(');
int indexOfLastCloseParen = s.lastIndexOf(')');
return new String[] {
s.substring(0, indexOfLastOpenParen),
s.substring(indexOfLastOpenParen + 1, indexOfLastCloseParen),
s.substring(indexOfLastCloseParen + 1)
};
}
public static void main(String args[]) throws Exception {
String input[] = {
"Xbox 360 (black) Elite Console 120GB (Mason City Illinois ) $200",
"$200 2013 North Trail Camper (RT 202. Manchester, Maine) $224/mo.",
"Snowmobile Bike trailers (Winthrop / Augusta) $40 Monthly",
"\"Great Xmas Gift\" XBox 360 Guitar Hero (Springfied)"
};
Pattern p = Pattern.compile("\\(([^\\)]+)\\)");
for (String s : input) {
System.out.println(Arrays.asList(splitParens(s)));
}
// =>
// [Xbox 360 (black) Elite Console 120GB , Mason City Illinois , $200]
// [$200 2013 North Trail Camper , RT 202. Manchester, Maine, $224/mo.]
// [Snowmobile Bike trailers , Winthrop / Augusta, $40 Monthly]
// ["Great Xmas Gift" XBox 360 Guitar Hero , Springfied, ]
}
当然,需要更多的错误检查(例如,如果没有(
或)
?)。