【问题标题】:java regex match is nulljava 正则表达式匹配为空
【发布时间】: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*(例如:1x012x053x11)或包含字符串Episode dated 的字符串,因为这些字符串指的是电视节目剧集,而不是电影,我试图将其分开。我还需要匹配电影标题和年份。

【问题讨论】:

  • 啊,是的。很好的收获,但我认为这不是问题。不过我会解决我的问题。

标签: java regex match


【解决方案1】:

问题主要在于这个j&lt;matcher.groupCount() 条件。您有三个组,但此条件将只打印除组 0 之外的两个组。将&lt; 转为&lt;= 将帮助您也打印最后一组。

for (int j=0; j<=matcher.groupCount(); j++) {
                Log.d("TAG2", "Match " + j + ": " + matcher.group(j));

为什么匹配 2 为空?

这是因为在负前瞻断言中存在捕获组。就像其他回答者所说,将捕获组转换为非捕获组不会创建额外的组。

Group 0 = Prints the entire match
Group 1 = Prints the characters which are present inside the group index 1.
Group 2 = Prints the characters which are present inside group index 2. Likewise it goes on.

【讨论】:

  • 哇,这真的很奇怪。我原以为这会导致索引超出范围异常,但它起作用了。
【解决方案2】:
^((?!.*(?:\d*x\d*|Episode dated)).*) \((\d*)\)$

 ^^     ^^                               ^^


Group1   Group2                          Group3  

Group2 是您获得的空组。在 regex101.com 中,您的年份 2002group 3 匹配。使第二组不捕获。

当您的字符串因为负前瞻而匹配时,Group2 不存在。所以它将为空。

查看演示。

https://www.regex101.com/r/oI2jF9/2

【讨论】:

  • 感谢您的回答,这有帮助。
猜你喜欢
  • 2018-03-24
  • 2011-03-30
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2013-07-09
相关资源
最近更新 更多