2010-03-26 38 views
9

是否有可能知道流/字符串是否包含可能與正則表達式匹配的輸入。java.util.regex.Pattern可以部分匹配嗎?

例如

String input="AA"; 
Pattern pat=Pattern.compile("AAAAAB"); 
Matcher matcher=pat.matcher(input); 
//<-- something here returning true ? 

String input="BB"; 
Pattern pat=Pattern.compile("AAAAAB"); 
Matcher matcher=pat.matcher(input); 
//<-- something here returning false ? 

感謝

+1

這不是真的如何正則表達式的工作。該模式應該是輸入的子字符串,或者沒有匹配。你可以寫自己的東西,但是它會像反向正則表達式。 如果你反轉'input'和'pattern'字符串,然後調用matcher.matches(輸入) - 你會得到你想要的。 – Kylar 2010-03-26 21:11:12

回答

11

是,Java提供了一個辦法做到這一點。首先,您必須調用其中一種標準方法來應用正則表達式,如matches()find()。如果返回false,您可以使用hitEnd()方法,以找出是否某些更長的字符串可能匹配:

String[] inputs = { "AA", "BB" }; 
Pattern p = Pattern.compile("AAAAAB"); 
Matcher m = p.matcher(""); 
for (String s : inputs) 
{ 
    m.reset(s); 
    System.out.printf("%s -- full match: %B; partial match: %B%n", 
        s, m.matches(), m.hitEnd()); 
} 

輸出:

AA -- full match: FALSE; partial match: TRUE 
BB -- full match: FALSE; partial match: FALSE 
0

是否Matcher.matches()你想要什麼不能做?

+0

他想要相反。他的模式是更長的字符串,他希望找到輸入匹配*到目前爲止*。 – jwismar 2010-03-26 21:29:26

-1

如果你只是想檢查一個字符串包含由一個正則表達式指定的一些模式:

String s = ...; 
s.matches(regex) 
8

其實,你是幸運的:Java的正則表達式確實有方法你想:

public boolean hitEnd()

返回true如果EN在由該匹配器執行的最後一次匹配操作中,輸入的d被搜索引擎擊中。

當此方法返回true時,則可能有更多輸入會改變上次搜索的結果。

所以你的情況:

String input="AA"; 
Pattern pat=Pattern.compile("AAB"); 
Matcher matcher=pat.matcher(input); 
System.out.println(matcher.matches()); // prints "false" 
System.out.println(matcher.hitEnd()); // prints "true" 
1

到hitEnd的替代方法是指定在RE本身的要求。

// Accepts up to 5 'A's or 5 'A's and a 'B' (and anything following) 
Pattern pat = Pattern.compile("^(?:A{1,5}$|A{5}B)"); 
boolean yes = pat.matcher("AA").find(); 
boolean no = pat.matcher("BB").find();