简体   繁体   中英

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

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

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"

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

Matcher.matches()不做你想做的吗?

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

String s = ...;
s.matches( regex )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM