【发布时间】:2018-05-08 09:58:42
【问题描述】:
我有一个String,其中包含 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.
【问题讨论】:
-
你能告诉我们更多关于输入的信息吗?例如,我可以看到公司信息以
(Ltd.)或Ltd.结尾是始终设置在那里还是可以更改? -
试试
\(((?:[^()]+|\([^\)]*\))*)\)。现场演示(右图):regex101.com/r/ppnfjy/1 -
您不应该将正则表达式用于嵌套结构。但如果你真的需要,请看这里:stackoverflow.com/questions/47162098/…
-
@ErwinBolwidt 您认为需要匹配有问题的嵌套括号吗?
-
@revo 你不是吗?