【发布时间】:2015-02-05 04:55:33
【问题描述】:
我正在尝试查找特定模式但也排除某些模式。出于某种原因,我的正则表达式在我的程序中不起作用,但它可以与在线正则表达式测试器一起使用。有什么问题?
这里是在线测试:regex101
这里是java测试:
private void TestRegex() {
ArrayList<String> strings = new ArrayList<>();
strings.add("Every Witch Way 3x19 New Witch Order (2015)");
strings.add("The Tonight Show Starring Jimmy Fallon Episode dated 22 January 2015 (2015)");
strings.add("October Gale (2014)");
strings.add("Kung Pow: Enter the Fist (2002)");
Pattern pattern = Pattern.compile("^((?!.*(\\d*x\\d*|Episode dated)).*) \\((\\d*)\\)$");
for (String s : strings) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
Log.d("TAG1", s);
for (int j=0; j<matcher.groupCount(); j++) {
Log.d("TAG2", "Match " + j + ": " + matcher.group(j));
}
}
}
}
这是我的测试的输出:
... D/TAG1﹕ October Gale (2014)
... D/TAG2﹕ Match 0: October Gale (2014)
... D/TAG2﹕ Match 1: October Gale
... D/TAG2﹕ Match 2: null
... D/TAG1﹕ Kung Pow: Enter the Fist (2002)
... D/TAG2﹕ Match 0: Kung Pow: Enter the Fist (2002)
... D/TAG2﹕ Match 1: Kung Pow: Enter the Fist
... D/TAG2﹕ Match 2: null
为什么匹配 2 为空?在在线匹配器中,两者都正确匹配。
正则表达式字符串的解释:
我想匹配格式为Movie Title (Year) 的所有字符串,并忽略所有包含字符串\d*x\d*(例如:1x01、2x05、3x11)或包含字符串Episode dated 的字符串,因为这些字符串指的是电视节目剧集,而不是电影,我试图将其分开。我还需要匹配电影标题和年份。
【问题讨论】:
-
啊,是的。很好的收获,但我认为这不是问题。不过我会解决我的问题。