0

我有一个这样的代码: -

Pattern pattern = Pattern.compile("((\\{(.*?)\\}\\{)|(\\{(.*?)\\}$))");
final Matcher matcher = pattern.matcher(str); 
int pos = 0;

while(true)
{
    if(matcher.find(pos))
    {
        ...
        pos--;
    }
    else
        break;
}

我看到的是 matcher.find(pos) 如果没有发生模式匹配,则会被阻止。如果输入字符串中没有匹配项,如何避免这种阻塞性质并让它出来。

4

2 回答 2

1

它不会阻塞,而是根据 str 内容无限循环。如果在 pos = 1 处找到匹配项,则 pos-- 返回初始状态的匹配器(到 pos = 0),这会导致无限循环

于 2013-08-02T03:10:40.483 回答
1

我想你正在寻找这样的东西。我猜你正试图在你的输入字符串(str)中找到每个模式。请参阅代码注释以了解实现。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternTest
{
   public static void main(String[] args)
   {
      String str = "{test1}{test2}{test3}{test4}";

      Pattern pattern = Pattern.compile("((\\{(.*?)\\}\\{)|(\\{(.*?)\\}$))");
      Matcher matcher = pattern.matcher(str);
      int pos = 0;

      while (true)
      {
         if (matcher.find(pos))
         {
            System.out.println("MATCH START: " + matcher.start());
            System.out.println("MATCH END: " + matcher.end());
            System.out.println("MATCH GROUP: " + matcher.group());
            System.out.println();

            // Move position to end of MATCH
            pos = matcher.end()-1;
         }
         else if(matcher.hitEnd())
         {
            // Break when matcher hit end
            break;
         }
         else
         {
            // No Match YET - Move position 1
            System.out.println("NO MATCH");
            pos++;
         }
      }
   }
}
于 2013-08-02T03:10:48.540 回答