I'd like to filter a list of strings based on complete regex match, ie only retain strings that fully match the regex. What's the canonical way to do this in Scala?
This is one long-winded way of getting the result I'd like (only returning "foo", not "foot"):
scala> val regex = "f*o".r
scala> List("foo","bar","foot").filter(regex.pattern.matcher(_).matches)
res24: List[String] = List(foo)
The filter expression seems long, but everything else (for instance involving unapplySeq) seems longer, or in the case of using String.matches, less efficient because it means recompiling the pattern every time. The best solution seem to be to pimp the Regex class:
implicit class RichRegex(underlying: Regex) {
def matches(s: String) = underlying.pattern.matcher(s).matches
}
So the code becomes:
scala> List("foo","bar","foot").filter(regex.matches)
res33: List[String] = List(foo)
I'm inclined to submit a pull-request to add this method to the Regex class, unless there is a better way to do this that I haven't thought of?
One alternative is to just add anchors (ie "^f.o$") to the regex expression, but this isn't too attractive to me - perhaps just because I'm used to the semantics of the Java Matcher.matches() method.