匹配字符串ArrayList中的模式

时间:2018-12-01 23:48:29

标签: java arrays pattern-matching

我正在尝试在ArrayList中的项目之间匹配模式。到目前为止,我已经完成了,但是有问题。我做到了,所以*与ArrayList中的任何项目匹配。以及我如何开始匹配​​是通过对第一个模式项进行indexOf来实现的,但是如果第一个项是*则不会起作用,因为它正在尝试对indexOf *进行索引项目。

所以基本上这里是代码。

public boolean matchPattern(String... strings) {
    int indexOfItem = getList().indexOf(strings[0]);
    if (indexOfItem != -1) {
        for (int i = 0; i < strings.length; i++) {
            int listIndex = indexOfItem + i;
            String s = strings[i];
            if (Objects.equals("*", s)) {
                continue;
            }
            if (!Objects.equals(getList().get(listIndex), s)) {
                return false;
            }
        }
        return true;
    }
    return false;
}

问题在此行上发生

int indexOfItem = getList().indexOf(strings[0]);

strings[0]返回*

有人可以告诉我如何使用*作为第一项吗?在这一点上我一无所知。基本上,模式会像这样

  

*,1、2、3,*,5

将成功匹配以下内容

  

0,1,2,3,4,5

  

随机,随机,0、1、2、3、4、5'

但不匹配

  

0,1,随机,3,4,5

  

随机,随机,0、1,随机,3、4、5

PS:这只是一个我真的不想匹配数字的例子。

2 个答案:

答案 0 :(得分:0)

由于您要进行模式匹配,因此可以使用正则表达式在一行中完成!

从输入中构建正则表达式,将通配符转换为"[^,]+",然后对其进行测试:

/** @return -1 if no hit, otherwise the index of the first element of the part that matches */
public int matchPattern(String... strings) {
    String head = getList().toString().replaceAll("(.*)?\\b" + String.join(", ", strings).replace("*", "[^,]+") + "\\b.*", "$1");
    return head.isEmpty() ? -1 : head.replaceAll("[^,]", "").length();
}

答案 1 :(得分:0)

提出一种适用于我尝试过的测试用例的解决方案,如果有人知道在某些情况下该代码是否会失败,请随时发布答案。

public static int findPattern(List<String> strings, String... pattern) {
    findFirstString:
    for (int startIndex = 0; startIndex <= strings.size() - pattern.length; startIndex++) {
        for (int i = 0; i < pattern.length; i++) {
            String p = pattern[i];
            if (!"*".equals(p) && !strings.get(startIndex + i).equals(p)) {
                continue findFirstString;
            }
        }
        return startIndex;
    }
    return -1;
}

然后我使用!= -1检查模式是否匹配,因为我正在向索引中注入一些数据。

相关问题