Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

java - Matcher's matches() method returns false, find() and groupCount() return results

I have the following code:

private static final String ET_AL = "(\p{Punct}|\b|^|\s)et\.? al\.?(\b|$|\s)";
private static final Pattern ET_AL_PATTERN = Pattern.compile(ET_AL, Pattern.CASE_INSENSITIVE);

...

Matcher m = ET_AL_PATTERN.matcher("Doe, J.; Brown, C.; et al");
while(m.find()) {
    System.out.println(m.group());
}
m.reset();
System.out.println(m.matches());

The loop prints "et al" but the call to m.matches() returns false. Also m.groupCount() returns 2. Any help about what is going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

but the call to m.matches() returns false.

It is because Matcher#matches() requires you to match complete input with your regex.

From Javadoc:

public boolean matches()

Attempts to match the entire region against the pattern. If the match succeeds then more information can be obtained via the start, end, and group methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...