This pitch has methods for both finding matches and checking if there is a match. However, there is a gap:
Has Match | Return Match | Anchoring |
---|---|---|
contains(_:) -> Bool |
firstMatch(of:) |
Unanchored |
starts(with:) -> Bool |
prefixMatch(of:) |
Anchored at start ^ |
??? |
wholeMatch(of:) |
Anchored at start and end ^...$ |
Is this intentional? If not, could it be added? Maybe matchesWhole(of:)
?
Related:
Should the ~=
operator be for anchored or unanchored matching (ie. wholeMatch
/matchesWhole
or firstMatch
/contains
)?
The two languages I’ve used that allow using Regex in a switch have gone for different options:
- Ruby does unanchored matching - see Class: Regexp (Ruby 3.1.2)
case "abcde"
when /bcd/
print "matched"
end
- Scala does anchored matching (unless
unanchored
is used)
val pattern = "bcd".r
"abcde" match {
case pattern(_*) => "Matches"
case _ => "No match"
}
The same behaviour can be achieved whether it's anchored or not:
Anchored:
switch "abcde" {
case /bcd/:
// no match
case /.*bcd.*/:
// matches
}
Unanchored
switch "abcde" {
case /^bcd$/:
// no match
case /bcd/:
// matches
}
I think the unanchored option is possibly less surprising?