为什么使用find()和“”作为模式时,matcher始终循环?

时间:2021-05-09 18:56:38

When given empty string as a pattern the following code loops forever. Why this code loops forever? Did I misuse find(int) method?

当给定空字符串作为模式时,以下代码将永远循环。为什么这个代码会一直循环?我是否误用了find(int)方法?

        Pattern pattern = Pattern.compile("");
        Matcher matcher = pattern.matcher("some text");    

        int pos = 0;
        int i = 0;
        while (matcher.find(pos))
        {
            int start = matcher.start();
            int end = matcher.end();
            pos = end;
            System.out.format("%d", i++);
        }

1 个解决方案

#1


2  

Since the pattern is an empty string, the pos value will always be zero. In this case, you don't need to pass the pos argument to find. Just call the no-arg find. Note that the two method overloads behave differently. For find(index):

由于模式是一个空字符串,所以pos值总是0。在这种情况下,您不需要传递pos参数来查找。就打电话给no-arg找。注意,这两个方法重载的行为不同。找到(指数):

Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.

重置此匹配器,然后尝试查找与模式匹配的输入序列的下一个子序列,从指定的索引开始。

For the no-arg find():

不带参数的发现():

Attempts to find the next subsequence of the input sequence that matches the pattern.

尝试查找与模式匹配的输入序列的下一个子序列。

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

此方法在此matcher区域的开始处开始,或者,如果之前对该方法的调用成功,并且此后一直没有重置该matcher,则在第一个字符上没有与前一个匹配匹配。

#1


2  

Since the pattern is an empty string, the pos value will always be zero. In this case, you don't need to pass the pos argument to find. Just call the no-arg find. Note that the two method overloads behave differently. For find(index):

由于模式是一个空字符串,所以pos值总是0。在这种情况下,您不需要传递pos参数来查找。就打电话给no-arg找。注意,这两个方法重载的行为不同。找到(指数):

Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.

重置此匹配器,然后尝试查找与模式匹配的输入序列的下一个子序列,从指定的索引开始。

For the no-arg find():

不带参数的发现():

Attempts to find the next subsequence of the input sequence that matches the pattern.

尝试查找与模式匹配的输入序列的下一个子序列。

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

此方法在此matcher区域的开始处开始,或者,如果之前对该方法的调用成功,并且此后一直没有重置该matcher,则在第一个字符上没有与前一个匹配匹配。