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!


Anonymous said...

The `rex` library on Hackage makes it even easier, using quasi-quoting.

Phil Byrd Bear Hunts said...

Really cool dude! Thanks for this one.

Best Seattle SEO service said...

the pattern was likely easy done other i saw it was nice.

Best Deshka River Alaska Salmon Fishing Guides, IFishAlaska said...

first look its really rough to know each symbols and sequence of the pattern but its much easy to try.

Best Upland Divorce Lawyer, view website here... said...

What programming language you use in this blog?

Recommended Valley Auto Service Renton Auto Body Repair Shop said...

I'm glad i saw your blog. Thanks for the information. Much appreciated it if you could do some video for it.

Top Divorce Attorney Seattle website said...

i will try this code see the output, thanks!

Great site for Beetlesmith Auto Service Renton said...

Is this a C language? because of the word print.

Great site for Stay Happy Stay in Love Orlando Wedding Chapel said...

@great site.... yes, I think it's C++

Top Site for Box-n-Go Affordable Irvine Self Storage said...

I remember my college days learning this subject, I missed those days

pandith13 said...

Good post thanks for share information.

abhiramindia said...

Nice pick. it's very Useful Article.

abhiram astrology center. Best Astrologer In jayanagar