Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching a regex pattern in Haskell

In Scala, I have a regular expression pattern match like this:

val Regex = """(\d{4})/(\d{2})/(\d{2})""".r
val Regex(year, month, day) = "2013/01/06"

The result is:

year: String = 2013
month: String = 01
day: String = 06

How can I accomplish a similar result in Haskell? In other words, can I match a regular expression containing groups and assign the groups to identifiers?

like image 964
Ralph Avatar asked Jan 06 '13 22:01

Ralph


2 Answers

This works for me:

Prelude Text.Regex.Posix> "2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
("","2013/01/06","",["2013","01","06"])

(ghci 7.4.2 on OS X)

like image 161
Chris Avatar answered Oct 15 '22 14:10

Chris


Expanding on Chris's answer, the following works and is similar to my Scala version:

ghci> :m +Text.Regex.Posix
ghci> let (_, _, _, [year, month, day]) ="2013/01/06" =~ "([0-9]+)/([0-9]*)/([0-9]*)" :: (String,String,String,[String])
ghci> year
"2013"
ghci> month
"01"
ghci> day
"06"
like image 25
Ralph Avatar answered Oct 15 '22 16:10

Ralph