2011-08-18 195 views
5

我有這個代碼,但它似乎並沒有工作。Java的正則表達式不匹配?

Pattern pattern=Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);"); 
Matcher matcher=pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com"); 
System.out.println(matcher.matches()); 

有人會知道爲什麼嗎?

+0

沒有什麼錯的正則表達式本身。當我用[RegexBuddy](http://www.regexbuddy.com/)測試它時,它工作。 –

+1

我知道。我知道正則表達式足以知道它會起作用。和RegexBuddy - 40美元!瘋!我只是堅持http://gskinner.com/RegExr/ – Isaac

回答

8

Matcher#matches()方法嘗試匹配整個輸入序列與模式。

Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*$"); //true 
Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);"); //false 
+0

嗯,不知道它匹配了整個序列,謝謝。 – Isaac

1

假設你的目標是提取IMGURSESSION

import java.util.regex.*; 

Pattern pattern = Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*"); 
Matcher matcher = pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com"); 
if (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

只要確保你在比賽中把所有的圖案在年底,以滿足「匹配」的語義。