我有一个包含2或3个公司名称的字符串,每个名称都用括号括起来。每个公司名称也可以包含括号中的单词。我需要使用正则表达式将它们分开,但找不到方法。
我的inputStr
:
(Motor (Sport) (racing) Ltd.) (Motorsport racing (Ltd.)) (Motorsport racing Ltd.)
or
(Motor (Sport) (racing) Ltd.) (Motorsport racing (Ltd.))
预期结果是:
str1 = Motor (Sport) (racing) Ltd.
str2 = Motorsport racing (Ltd.)
str3 = Motorsport racing Ltd.
我的代码:
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++;
}
这对于str2
和str3
非常有效,但对于str1
则不行。
当前结果:
str1 = Motor (Sport)
str2 = Motorsport racing (Ltd.)
str3 = Motorsport racing Ltd.
\(((?:[^()]+|\([^\)]*\))*)\)
。实时演示(匹配在右侧):https://regex101.com/r/ppnfjy/1 - revo