gpt4 book ai didi

haskell - 使用 parsec 在字符串中查找子字符串

转载 作者:行者123 更新时间:2023-12-05 03:12:41 27 4
gpt4 key购买 nike

例如,我想从 "aabbccabc" 获取 "abc",使用正则表达式应该很容易。但我想使用秒差距。看起来 try 可以做到这一点,但那肯定是相当低效的......

我试过:

import Text.ParserCombinators.Parsec
ps pser txt = case (parse pser "" txt ) of
Left e -> show e
Right v -> v

得到如下结果:

λ> ps (string "asf") "  dsfdsasf"
"(line 1, column 1):\nunexpected \" \"\nexpecting \"asf\""

最佳答案

你可以这样做:

{-# LANGUAGE FlexibleContexts #-}

import Text.Parsec
import Text.Parsec.Char

findSubString str = try (string str) <|> (anyChar *> findSubString str)

foo = do
findSubString "abc"
findSubString "def"

test1 = parseTest foo "this is abc" -- fails: expecting def

test2 = parseTest foo "this is abc and de" -- fails: expecting def

test3 = parseTest foo "this is abc and def" -- succeeds

关于haskell - 使用 parsec 在字符串中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32911567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com