Warm tip: This article is reproduced from serverfault.com, please click

其他-你如何在Haskell中陈述正则表达式模式?

(其他 - How do you state a regex pattern in Haskell?)

发布于 2020-11-28 11:50:34

我正在尝试使用以下代码进行正则表达式替换

import Text.RE.Replace
import Text.RE.TDFA.String

onlyLetters :: String -> String
onlyLetters s = replaceAll "" $ s *=~ [re|$([^a-zA-Z])|]

我发现很难找到任何可理解的文档。这会产生编译错误:

    src\Pangram.hs:6:53: error: parse error on input `]'
  |
6 | onlyLetters s = replaceAll "" $ (s *=~ [re|[a-zA-Z]|])
  |                                                     ^

Progress 1/2

--  While building package pangram-2.0.0.12 (scroll up to its section to see the error) using:
      C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_3.0.1.0_ghc-8.8.4.exe --builddir=.stack-work\dist\29cc6475 build lib:pangram test:test --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1
PS C:\Users\mcleg\Exercism\haskell\pangram> stack test
pangram> configure (lib + test)
Configuring pangram-2.0.0.12...
pangram> build (lib + test)
Preprocessing library for pangram-2.0.0.12..
Building library for pangram-2.0.0.12..
[1 of 2] Compiling Pangram

src\Pangram.hs:7:56: error: parse error on input `]'
  |
7 | onlyLetters s = replaceAll "" $ s *=~ [re|$([^a-zA-Z])|]
  |                                                        ^

Progress 1/2

--  While building package pangram-2.0.0.12 (scroll up to its section to see the error) using:
      C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_3.0.1.0_ghc-8.8.4.exe --builddir=.stack-work\dist\29cc6475 build lib:pangram test:test --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1

该支架有什么问题,我该如何正确执行?谢谢-斯凯

Questioner
Skye Sprung
Viewed
11
Willem Van Onsem 2020-11-28 19:56:18

[…|…|]准报价语法[哈斯克尔维基]这是Haskell语法的扩展,默认情况下未启用。

你可以使用一个LANGUAGE编译指示来打开它

{-# LANGUAGE QuasiQuotes #-}

import Text.RE.Replace
import Text.RE.TDFA.String

onlyLetters :: String -> String
onlyLetters s = replaceAll "" $ s *=~ [re|$([^a-zA-Z])|]

准引用将生成Haskell代码,然后在Haskell程序中使用该代码。这意味着通过准报价,可以在编译时对正则表达式进行验证,与在运行时编译正则表达式相比,它甚至可以稍微优化效率。

对于给定的onlyLetters函数,我们将得到:

*Main> onlyLetters "fo0b4r"
"fobr"