Monday, August 17, 2009

Regex and Option trick

Neat trick:

def findBetween(s: String, p1: String, p2: String) = (
findFirstMatchIn s
map (_ group 1)
getOrElse ""

The trick here is that map, on an Option, applies the function if the option is Some, otherwise returns None. So I get to convert my Match into a particular group before I check if I got anything at all and return a default if not.