Last active
December 16, 2015 21:09
-
-
Save courtarro/c6b296e25c9a43923e6d to your computer and use it in GitHub Desktop.
Wrapper for Java's Matcher object that implements the basic MatchResult interface and provides a convenient one-call version of matches() for use in if-elseif-else statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.MatchResult; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Wrapper for the built-in object Matcher that runs a pattern matcher and saves | |
* the results in the same method call. Call matches() first to set up the | |
* internal matcher, then call the other methods to operate on the results. | |
* | |
* @author Ethan Trewhitt | |
*/ | |
public class BetterMatcher implements MatchResult { | |
private Matcher matcher = null; | |
public BetterMatcher() { } | |
public boolean matches(Pattern pattern, String text) { | |
matcher = pattern.matcher(text); | |
return matcher.matches(); | |
} | |
private Matcher getMatcher() { | |
if (matcher == null) | |
throw new IllegalStateException("Have not yet tested for matches. Execute matches() first."); | |
else | |
return matcher; | |
} | |
@Override | |
public int start() { | |
return getMatcher().start(); | |
} | |
@Override | |
public int start(int group) { | |
return getMatcher().start(group); | |
} | |
@Override | |
public int end() { | |
return getMatcher().end(); | |
} | |
@Override | |
public int end(int group) { | |
return getMatcher().end(group); | |
} | |
@Override | |
public String group() { | |
return getMatcher().group(); | |
} | |
@Override | |
public String group(int group) { | |
return getMatcher().group(group); | |
} | |
@Override | |
public int groupCount() { | |
return getMatcher().groupCount(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment