为什么regex =“”(空模式)在每个字符位置都匹配?

时间:2018-08-25 09:11:43

标签: java regex string

我有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.

1 个答案:

答案 0 :(得分:1)

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

注意:如果您将find更改为match,则应该发现没有匹配项。 (对于match,该模式需要匹配整个输入,并且整个输入不匹配零字符序列。)


在编辑问题之前,您的模式为Pattern("e*")。这意味着字符'e'的重复次数为零或更多。根据上述逻辑,您可以在输入中每个字符位置“查找”一个。