Using regexp in haskell security features

I would like to write a Haskell function whose behavior depends on the regex pattern corresponding to one of the arguments. In a language like C / Python / Perl, I would definitely use the big if / else construct, but I don't have that option. What is the most idiomatic way for Haskell to handle this?

I looked at the guards, but they do not work: No instance for (Data.String.IsString source0) :

 function arg | arg =~ "pattern1" = dothis arg | arg =~ "pattern2" = dothat arg | otherwise = failwith arg 

The pattern comparison used in case constructs would be ideal if it handled Regex.

 function arg = case arg of (pattern1 match) -> dothis match (pattern2 match) -> dothat match _ -> failwith arg 
+8
idioms regex haskell
source share
1 answer

Your first example works for me:

 import Text.Regex.Posix function :: String -> String function arg | arg =~ "pattern1" = "1" | arg =~ "pattern2" = "2" | otherwise = "3" 

I think your IsString error is related to an overloaded string literal extension. Try disabling this, or try using explicit String strings:

 function :: String -> String function arg | arg =~ ("pattern1"::String) = "1" | arg =~ ("pattern2"::String) = "2" | otherwise = "3" 

Too loud? You can push the crack in the last lines.

 function2 :: String -> String function2 arg | arg =~ s"pattern1" = "1" | arg =~ s"pattern2" = "2" | otherwise = "3" where s :: String -> String s = id 

Do you need subgroup matching?

 function3 :: String -> String function3 arg | [_,x]:_ <- arg =~ s"pat(t*)ern1" = "matched group: " ++ x -- ... 

In function3 "patttern1" variable x will be bound to "tt" . On function3 "xyz" test will fail and the next branch will be checked.

+12
source share

All Articles