简体   繁体   English

在haskell函数保护中使用regexp

[英]Using regexp in haskell function guards

I would like to write a Haskell function that's behavior is dependent upon regex pattern matching one of the arguments. 我想编写一个Haskell函数,其行为依赖于匹配其中一个参数的正则表达式模式。 In a language like C/Python/Perl, I would definitely just use a large if/else construct, but I don't really have that option. 在像C / Python / Perl这样的语言中,我肯定会使用一个大的if / else结构,但我真的没有那个选项。 What is the most idiomatic Haskell way to handle this? 什么是最惯用的Haskell处理方法?

I've considered guards, but they don't work: No instance for (Data.String.IsString source0) : 我已经考虑过警卫,但它们不起作用: No instance for (Data.String.IsString source0)

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

The pattern matching used in case constructs would be perfect, if it handled Regex. 如果处理正则表达式,在案例结构中使用的模式匹配将是完美的。

function arg = case arg of
  (pattern1 match) -> dothis match
  (pattern2 match) -> dothat match
  _ -> failwith arg

Your first example does work 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 due to the overloaded string literals extension. 我认为您的IsString错误是由于重载的字符串文字扩展名。 Try to disable that, or alternatively try to use explicit String strings: 尝试禁用它,或者尝试使用显式String字符串:

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

Too noisy? 太吵了? You can push the cruft to the last lines. 你可以把残骸推到最后一行。

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

Need subgroup matching? 需要子组匹配吗?

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

On function3 "patttern1" , variable x will be bound to "tt" . function3 "patttern1" ,变量x将绑定到"tt" On function3 "xyz" , the test will fail and the next branch will be tried. function3 "xyz" ,测试将失败并尝试下一个分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM