我有这个String变量:
String a = "Chris Weitz (screenplay), Tony Gilroy (screenplay) Lucasfilm Allison Shearmur Productions Black Hangar Studios";
它可以包含一个或两个“名字Surename(作业)”模式,用逗号分隔。
如何使用正则表达式成功切割除了这些模式之外的所有内容?它最终应该是这样的:
a = "Chris Weitz (screenplay), Tony Gilroy (screenplay)";
或者像这样:
a = "Chris Weitt (screenplay)";
谢谢你们。
答案 0 :(得分:1)
String s = "Chris Weitz (screenplay), Tony Gilroy (screenplay) Lucasfilm Allison Shearmur Productions Black Hangar Studios";
Pattern p = Pattern.compile("[^,\\(]+\\([^\\)]+\\)");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group().trim());
}
答案 1 :(得分:0)
从上一个)
开始删除(即替换为空白):
str = str.replaceAll("\\)[^)]*$", ")");
正则表达式将结束括号与结尾匹配,而不会遇到另一个结束括号。
答案 2 :(得分:0)
阐述Gurwinder Singh的回答......(并改变正则表达式)
String s = "Chris Weitz (screenplay), Tony Gilroy (screenplay) Lucasfilm Allison Shearmur Productions Black Hangar Studios";
Pattern p = Pattern.compile("([[:alpha:] ]+\\([[:alpha:]]+\\))");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group().trim());
}
这个想法是匹配一个给定模式的字符串 - ([[:alpha:] ]+\([[:alpha:]]+\))
- 它基本上捕获了一对括号后跟的任何单词。 - regex101