tags:

views:

294

answers:

5

Hi all,

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

+1  A: 

Does Matcher.matches() not do what you want ?

Brian Agnew
He wants the reverse. His pattern is the longer string, he wants to find out of the input matches *so far*.
jwismar
+1  A: 

If you just want to check if a string contains some pattern specified by a regex:

String s = ...;
s.matches( regex )
Manuel Darveau
+3  A: 

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
Alan Moore
+2  A: 

Actually, you are in luck: Java's regex does have the method you want:

public boolean hitEnd()

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

When this method returns true, then it is possible that more input would have changed the result of the last search.

So in your case:

String input="AA";
Pattern pat=Pattern.compile("AAB");
Matcher matcher=pat.matcher(input);
System.out.println(matcher.matches()); // prints "false"
System.out.println(matcher.hitEnd());  // prints "true"
polygenelubricants
A: 

An alternative to hitEnd is to specify the requirement in the RE itself.

// Accepts up to 5 'A's or 5 'A's and a 'B' (and anything following)
Pattern pat = Pattern.compile("^(?:A{1,5}$|A{5}B)");
boolean yes = pat.matcher("AA").find();
boolean no = pat.matcher("BB").find();
nicerobot