I have a String
that contains 2 or 3 company names each enclosed in parentheses. Each company name can also contains words in parentheses. I need to separate them using regular expressions but didn't find how.
My inputStr
:
(Motor (Sport) (racing) Ltd.) (Motorsport racing (Ltd.)) (Motorsport racing Ltd.)
or
(Motor (Sport) (racing) Ltd.) (Motorsport racing (Ltd.))
The expected result is:
str1 = Motor (Sport) (racing) Ltd.
str2 = Motorsport racing (Ltd.)
str3 = Motorsport racing Ltd.
My code:
String str1, str2, str3;
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(inputStr);
int index = 0;
while(m.find()) {
String text = m.group(1);
text = text != null && StringUtils.countMatches(text, "(") != StringUtils.countMatches(text, ")") ? text + ")" : text;
if (index == 0) {
str1= text;
} else if (index == 1) {
str2 = text;
} else if (index == 2) {
str3 = text;
}
index++;
}
This works great for str2
and str3
but not for str1
.
Current result:
str1 = Motor (Sport)
str2 = Motorsport racing (Ltd.)
str3 = Motorsport racing Ltd.