与 Java Matcher 匹配的正则表达式不会按预期找到



这是我遇到问题的正则表达式:^(?:(S+?)(?:s+|s*$)) .我正在尝试在以下String中匹配此模式的 3 次出现: -execution thisIsTest1 thisIsTest2 .下面是抓取前 numberOfArgs 个元素并返回填充了匹配项的List<String>的方法。问题是:返回List的大小为 1....循环总是迭代一次,然后退出...

private final String arguments="-execution  thisIsTest1  thisIsTest2";
 /**
 * Split the first N arguments separated with one or more whitespaces.
 * @return the array of size numberOfArgs containing the matched elements.
 */
...
public List<String> fragmentFirstN(int numberOfArgs){
    Pattern patt = Pattern.compile("^(?:(\S+?)(?:\s+|\s*$))",Pattern.MULTILINE);
    Matcher matc = patt.matcher(arguments);
    ArrayList<String> args = new ArrayList<>();
    logg.info(arguments);
    int i = 0;
    while(matc.find()&&i<numberOfArgs){
        args.add(matc.group(1));
        i++;
    }
    return args;
}

这是测试类:

private String[] argArr={"-execution",
        "thisIsTest1",
        "thisIsTest2"
};
...
@Test
public void testFragmentFirstN() throws Exception {
    List<String> arr = test.fragmentFirstN(3);
    assertNotNull(arr);
    System.out.println(arr); ----> prints : [-execution]
    System.out.println(test.getArguments()); ----> prints : -execution  thisIsTest1  thisIsTest2 <-----
    assertEquals(argArr[0],arr.get(0));
--->assertEquals(argArr[1],arr.get(1));<---- IndexOutOfBoundException : Index: 1, Size: 1
    assertEquals(argArr[2],arr.get(2));
    assertEquals(3,arr.size());
}

我认为Matcher#find()循环时会匹配所有可能的字符序列。我错过了什么?

问题是正则表达式有一个与输入字符串的开头^字符)匹配的边界匹配器。第一次在循环中调用 Matcher.find() 时,匹配的子字符串-execution 。这是因为-execution从字符串的开头开始,并且正则表达式具有部分(?:\s+|\s*$),这意味着在输入字符串的末尾检测空格字符(-execution之后就是这种情况)或非空格字符。

第二次迭代不会匹配任何字符串,因为匹配器不再位于输入字符串的开头。因此Matcher.find()返回 false。

您可以尝试删除该字符:

Pattern patt = Pattern.compile("(?:(\S+?)(?:\s+|\s*$))",
            Pattern.MULTILINE);

编辑:

根据 @ajb 的注释,只需删除^字符将使正则表达式匹配以空格开头的输入字符串。如果不需要这样做,您可以改为将^替换为G,这标志着匹配器上一个匹配的结束:

Pattern patt = Pattern.compile("\G(?:(\S+?)(?:\s+|\s*$))",
            Pattern.MULTILINE);

最新更新