2013-08-02 57 views
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)如果模式匹配不列入發生遭到封鎖。如何避免這種阻塞性質,並在輸入字符串中沒有匹配的情況下出現。

+2

什麼是您的輸入字符串?這不應該發生。你確定這個'......'不會讓你無限期地循環嗎? –

回答

1

它不阻止但根據str內容無限循環。如果你在pos = 1找到一個匹配,那麼pos--返回匹配器在初始狀態(到pos = 0),這會導致一個無限循環

+0

'Matcher'如果其'start'參數引發[exception](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find(int)) ('pos')爲負值。如果我們忽略'...','pos'在第一次循環後只能是負數。 –

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++; 
     } 
     } 
    } 
} 
+0

是的,如果錯過了休息,現在工作正常。 – user2465439