有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正则表达式找不到字符串

我对此代码有问题: 由于某些原因,它总是与代码不匹配

for (int i = 0; i < pluginList.size(); i++) {
    System.out.println("");
    String findMe = "plugins".concat(FILE_SEPARATOR).concat(pluginList.get(i));

    Pattern pattern = Pattern.compile("("+name.getPath()+")(.*)");
    Matcher matcher = pattern.matcher(findMe);

    // Check if the current plugin matches the string.
    if (matcher.find()) {
        return !pluginListMode;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    现在我们只能猜测,因为我们不知道name.getPath()会返回什么

    我怀疑它失败了,因为该字符串可能包含在正则表达式中具有特殊意义的字符。请再试一次

    Pattern pattern = Pattern.compile("("+Pattern.quote(name.getPath())+")(.*)");
    

    然后看看会发生什么

    而且(.*)部分(甚至是name.getPath()结果周围的括号)似乎根本不重要,因为你没有对匹配结果本身做任何事情。在这一点上,问题是为什么要首先使用正则表达式

  2. # 2 楼答案

    你真正需要的是

    return ("plugins"+FILE_SEPARATOR+pluginName).indexOf(name.getPath()) != -1;
    

    但是您的代码也没有意义,因为for循环无法进入它无条件返回的第二次迭代。所以你更可能需要这样的东西:

    for (String pluginName : pluginList)
      if (("plugins"+FILE_SEPARATOR+pluginName).indexOf(name.getPath()) != -1)
        return false;
    return true;