11

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?

4
  • 1
    See chapter 8 of Real world Haskell: book.realworldhaskell.org/read/… Commented Jan 6, 2013 at 22:43
  • 3
    I actually have the book open at this moment. The examples are outdated and several do not compile with GHC 7.4. Commented Jan 6, 2013 at 22:45
  • Looks like you are using dates: doesn't haskell has a date parsing library? Commented Jan 6, 2013 at 23:07
  • That is actually just a made-up example. My actual regex is much more complicated. Commented Jan 7, 2013 at 10:07

2 Answers 2

16

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I tried that return type and it works for me too. I'll post a small variant of your answer to include the extraction of the year, month, and day.
This does not work in the Posix parser, but does in the PCRE parser: let (_, _, _, [year, month, day]) ="2013/01/06" =~ "(\\d{4})/(\\d{2})/(\\d{2})" :: (String,String,String,[String])
Note that Text.Regex.Posix uses POSIX style regular expressions. It is also buggy on Windows. If you want this API, regex-tdfa-compat is a better choice
10

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.