package MusicLandscape.util.matcher;
import MusicLandscape.entities.Track;
import MusicLandscape.util.MyMatcher;
import java.util.regex.Pattern;package MusicLandscape.util.matcher;
import MusicLandscape.entities.Track;
import MusicLandscape.util.MyMatcher;
import java.util.regex.Pattern;The only interesting thing I did here is that in matches() I augment
the string pattern with some regular expression features.
/**
* Encapsulates the concept of matching a track based on its title.
* <p>
* This class is used to test whether a given track's title starts with a certain string,
* the starting string being the pattern of this matcher.
* <p>
* The pattern is a simple string. Null patterns are not accepted.
*
* @author Jonas Altrock (ew20b126@technikum-wien.at)
* @version 1
* @since ExerciseSheet05
*/
public class TitleMatcher extends MyMatcher<Track> {
/**
* The pattern to match the beginning of a Track title.
*/
private String pattern;
/**
* Creates a Matcher object with a specified pattern.<br>
*
* @param pat the pattern of this matcher
*/
public TitleMatcher(String pat) {
super(pat);
if (pat == null) {
throw new NullPointerException("TitleMatcher does not accept null as pattern!");
}
}
/**
* Matches an object against the pattern of this matcher.
*
* @param track the object to match
* @return whether t matches the pattern of this matcher.
*/
@Override
public boolean matches(Track track) {^ means “at the start of the string”. This matcher will
only match if the title of the track starts with the pattern..* means any character (.) repeated zero or more times (*).
That is regular expression pattern for “eat the rest of the string”.
This is not really necessary, but I try to always write my regular
expressions so that they match the full input string. return track.getTitle().matches("^" + pattern + ".*");
}
/**
* Sets the pattern of this matcher.
* <p>
* Null is not accepted.
*
* @param pat the pattern to set
*/
@Override
public void setPattern(String pat) {
if (pat == null) {
return;
}
pattern = pat;
}
/**
* Gets the pattern of this matcher.
* <p>
* The pattern is returned in a format that is considered valid in setPattern.
*
* @return the pattern
*/
@Override
public String getPattern() {
return pattern;
}
/**
* the string representation is <kbd>title starts with (PATTERN)</kbd>
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return "title starts with (" + pattern + ")";
}
}