使用Text.Combinators.Parsec进行不区分大小写的解析最简洁的方法是什么?

dan*_*dan 15 haskell parsec

我正在用Parsec写我的第一个程序.我想解析MySQL模式转储,并想提出一种很好的方法来解析表示某些关键字的字符串,不区分大小写.下面是一些代码,显示了我用来解析"CREATE"或"create"的方法.有一个更好的方法吗?不使用buildExpressionParser的答案是最好的.我在这里采取婴儿步骤.

  p_create_t :: GenParser Char st Statement
  p_create_t = do
      x <- (string "CREATE" <|> string "create")
      xs <- manyTill anyChar (char ';')
      return $ CreateTable (x ++ xs) []  -- refine later
Run Code Online (Sandbox Code Playgroud)

Hea*_*ink 18

您可以使用字符解析器构建不区分大小写的解析器.

-- Match the lowercase or uppercase form of 'c'
caseInsensitiveChar c = char (toLower c) <|> char (toUpper c)

-- Match the string 's', accepting either lowercase or uppercase form of each character 
caseInsensitiveString s = try (mapM caseInsensitiveChar s) <?> "\"" ++ s ++ "\""
Run Code Online (Sandbox Code Playgroud)


C. *_*ann 8

重复我在评论中所说的内容,因为它显然很有帮助:

这里简单的大锤解决方案是toLower在运行解析器之前简单地映射整个输入,然后以小写形式完成所有关键字匹配.

如果您在某些地方解析需要不区分大小写的内容而在其他地方需要区分大小写,或者如果您因为美观原因需要保留大小写,则会出现明显的困难.例如,尽管HTML标记不区分大小写,但在解析它时将整个网页转换为小写可能是不合需要的.即使在编译不区分大小写的编程语言时,转换标识符也会很烦人,因为任何产生的错误消息都与程序员编写的不匹配.