开发者

Java Regex not matching?

I have this code, but it does not seem to be working.

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

Would anyo开发者_如何转开发ne know why?


Matcher#matches() method attempts to match the entire input sequence against the pattern.

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


the matches Method match against the entire input string.

if you will match only a subsequence you can use the find() method.

the 3 different ways to match with a matcher are explained in the java docs: http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html


Assuming your aim is to extract the 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));
}

Just make sure you put in a match all pattern at the end to satisfy the "matcher" semantics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜