首页 > 解决方案 > 为什么 regex="" (一个空模式)在每个字符位置都匹配?

问题描述

我有regex=""一个String str="stackoveflow";

我不明白为什么它匹配字符串中的每个字符。你能给我解释一下吗?

public class test {

    public static void main(String[] args){
        Console console = System.console();
        String str="stackoveflow";          
        Pattern pattern = Pattern.compile("");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
        console.format("I found the text" +
            " \"%s\" starting at " +
            "index %d and ending at index %d.%n",
            matcher.group(),
            matcher.start(),
            matcher.end());     
        }
    }
}

输出是:

I found the text "" starting at index 0 and ending at index 0.
I found the text "" starting at index 1 and ending at index 1.
I found the text "" starting at index 2 and ending at index 2.
I found the text "" starting at index 3 and ending at index 3.
I found the text "" starting at index 4 and ending at index 4.
I found the text "" starting at index 5 and ending at index 5.
I found the text "" starting at index 6 and ending at index 6.
I found the text "" starting at index 7 and ending at index 7.
I found the text "" starting at index 8 and ending at index 8.
I found the text "" starting at index 9 and ending at index 9.
I found the text "" starting at index 10 and ending at index 10.
I found the text "" starting at index 11 and ending at index 11.
I found the text "" starting at index 12 and ending at index 12.

标签: javaregexstring

解决方案


Pattern("")匹配由零个字符组成的字符串。您可以在字符串的每个位置找到其中一个。

注意:如果您更改findmatch,您应该会发现没有匹配项。(与match模式需要匹配整个输入,而整个输入不匹配零字符序列。)


在您编辑问题之前,您的模式是Pattern("e*"). 这意味着字符的零次或多次重复'e'。通过上面的逻辑,您可以在输入中的每个字符位置“找到”其中一个。


推荐阅读