2011-08-18 190 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)); 
} 

只要确保你在比赛中把所有的图案在年底,以满足“匹配”的语义。