Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Can java.util.regex.Pattern do partial matches?

Is it possible to know if a stream/string contains an input that could match a regular expression.

For example

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

or

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

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, Java provides a way to do that. First you have to call one of the standard methods to apply the regex, like matches() or find(). If that returns false, you can use the hitEnd() method to find out if some longer string could have matched:

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());
}

output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...