2012-07-09 24 views
16

假設一個Regular Expression,其中,經由一個Java Matcher對象,是對大量的字符串匹配:Java模式匹配器:創建新的或重置?

String expression = ...; // The Regular Expression 
Pattern pattern = Pattern.compile(expression); 
String[] ALL_INPUT = ...; // The large number of strings to be matched 

Matcher matcher; // Declare but not initialize a Matcher 

for (String input:ALL_INPUT) 
{ 
    matcher = pattern.matcher(input); // Create a new Matcher 

    if (matcher.matches()) // Or whatever other matcher check 
    { 
     // Whatever processing 
    } 
} 

Java SE 6 JavaDoc for Matcher,人們發現重用相同Matcher對象的選擇,經由所述reset(CharSequence)方法,其中,作爲源代碼顯示,有點不是創建一個新Matcher每一次,即,不像上述比較便宜,一個可以這樣做:

String expression = ...; // The Regular Expression 
Pattern pattern = Pattern.compile(expression); 
String[] ALL_INPUT = ...; // The large number of strings to be matched 

Matcher matcher = pattern.matcher(""); // Declare and initialize a matcher 

for (String input:ALL_INPUT) 
{ 
    matcher.reset(input); // Reuse the same matcher 

    if (matcher.matches()) // Or whatever other matcher check 
    { 
     // Whatever processing 
    } 
} 

如果一個使用reset(CharSequence)模式或者他們是否應該每次都初始化一個新的對象Matcher

+6

通過一切手段重用'匹配器'。創建一個新的「匹配器」的唯一好理由是確保線程安全。這就是爲什麼你不用做一個'public static Matcher m' ---事實上,這就是爲什麼一個單獨的'Pattern'類首先存在的原因。 – 2012-07-09 08:22:44

+2

因此,對於單線程應用程序,甚至作爲實例或類變量,或者對於在方法內部創建Matcher對象的多線程應用程序,reset()很好,是嗎? – PNS 2012-07-09 08:25:26

+1

@MarkoTopolnik:我認爲從應用程序中分離正則表達式的編譯是擁有'Pattern'類的另一個好的理由。 – 2012-07-09 08:26:18

回答

24

務必重複使用Matcher。創建新的Matcher的唯一好理由是確保線程安全。這就是爲什麼您實際上不會生成public static Matcher m —,這就是爲什麼一個單獨的線程安全的Pattern工廠對象首先存在的原因。

在任何情況下,如果您確定在任何時間點只有一個用戶Matcher,可以通過reset重複使用。