Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Friday, September 06, 2013

Regex in Haskell patterns

Have you ever wanted to do case expr of regexhere -> ... ?
You can do almost that with view patterns!

{-# LANGUAGE ViewPatterns #-}

import Text.Regex.Posix

-- Helper
pat :: String -> String -> [[String]]
pat p s = s =~ p

-- Function with matching
foo :: String -> String
foo (pat "foo(bar|baz)" -> [[_,x]]) = x
foo _ = "no!"

main :: IO ()
main = do
  print $ foo "foobar"
  print $ foo "foobaz"
  print $ foo "yes?"

The above code will print bar baz no! . Have fun!