【问题标题】:Haskell RegEx Matching on UTF8 fileUTF8文件上的Haskell RegEx匹配
【发布时间】:2021-04-18 10:22:02
【问题描述】:

这个函数是我写的

module PdfParser (parseOptions) where

import Text.Regex.PCRE
import Data.List.Split

parseOptions :: String -> [String]
parseOptions s = splitOn "\n" (s =~ regex :: String)
  where 
    regex = "(?<=OPTIONS\n)((.|\n)*?)(?=INTERIEUR|INTÉRIEUR|EQUIPEMENTS DE SERIE)"

然后测试

module PdfParserSpec (spec) where

import Test.Hspec
import Test.QuickCheck
import PdfParser(parseOptions)

spec :: Spec
spec =  do
  describe "PdfParser (parseOptions)" $ do
    it "return List of options" $ do
      referencialText <- readFile "test/assets/referential.txt"
      parseOptions referencialText `shouldBe` [
        "Peinture métallisée 550 €"
        ,"Jantes alliage 17\" Viva Stella [RDIF21] 300 €"
        ,"Chargeur sans fil 250 €"
        ,"Roue de secours tôle [RSEC01] 150 €"]

但是当我阅读文本文件时,我所有的字符 éè 等都被 \233f\233 替换。然后我的正则表达式不起作用。

测试结果:

 test/PdfParserSpec.hs:12:7: 
  1) PdfParser, PdfParser (parseOptions), return List of options
       expected: ["Peinture m\233tallis\233e 550 \8364","Jantes alliage 17\" Viva Stella [RDIF21] 300 \8364","Chargeur sans fil 250 \8364","Roue de secours t\244le [RSEC01] 150 \8364"]
        but got: ["s alliage 17\" Viva Stella [RDIF21] 300 \8364","Chargeur sans fil 250 \8364","Roue de secours t\244le [RSEC01] 150 \8364","INT\201RIEUR","Sellerie Zen (Au lieu de Selleri"]

我的正则表达式处理我的文件 -> https://regex101.com/r/HYBmMh/1

我该如何解决这个问题?

【问题讨论】:

  • 这些没有替换为\233等。这就是字符串表示的方式。例如,双引号也不是字符串的一部分。
  • 永远不要使用(.|\n)*?,总是使用带有DOTALL修饰符的点,或者[\s\S]*?/[\w\W]*?/[\d\D]*?作为解决方法。
  • 当我用 [\s\S]* 替换时?我得到编译器错误“字符's'处的字符串/字符文字中的词法错误”
  • @Antonin:您应该使用[\\s\\S]*?,原因与您在第一条评论中转义字符的原因完全相同。
  • @WillemVanOnsem 谢谢你 :) 但是我的比赛有一个偏移量。 github.com/audreyt/regex-pcre-builtin/issues/3这就是为什么我认为它不起作用:(

标签: regex haskell encoding pcre


【解决方案1】:

我将 hackage regex-pcre-builtin 更改为 light-pcre。它有效!

我必须将我的字符串编码为 ut8 字节串,然后添加 utf8 编译时标志

module PdfParser (parseOptions) where

import Text.Regex.PCRE.Light(compile, utf8, match)
import Data.ByteString.UTF8(toString, fromString)
import Data.List.Split
import Data.String.Utils(strip)

parseOptions :: String -> Maybe [String]
parseOptions s = (splitOn "\n" . strip . toString . (!!0)) <$> (match regex (fromString s) [])
  where 
    regex = compile (fromString "(?<=OPTIONS\n)([\\s\\S]*?)(?=INTÉRIEUR)") [utf8]

感谢您的 cmets :)

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多