Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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

like image 647
Pierre Avatar asked Mar 26 '10 21:03

Pierre


1 Answers

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
like image 57
Alan Moore Avatar answered Oct 07 '22 10:10

Alan Moore