gpt4 book ai didi

regex - Haskell 中使用 parsec 或 attoparsec 的两个字符串之间的非贪婪匹配

转载 作者:行者123 更新时间:2023-12-02 21:22:12 29 4
gpt4 key购买 nike

这是我正在努力解决的问题。

使用诸如 parsecattoparsec 之类的解析器组合器,我想匹配以下字符串中的“match me”:

“此字符串之后的前噪声匹配与我匹配在我之前匹配我的后噪声之前匹配”

其中前噪声匹配我后噪声可以是任何字符串

这是问题解决方案的正则表达式版本:

(?<=match after this string)(.*?)(?=match before me)

如您所见,它是非贪婪的(.*?)。换句话说,它不会像 (.*) 那样匹配 "match me match before me"

作为记录,以下是我的许多悲惨尝试中的一些

在秒差距中,有 Between,但我对如何使用它感到困惑。 The documentation for it有示例 braces = Between (symbol "{") (symbol "}"),但我什至无法让示例本身正常工作。

我还尝试过“开始匹配结束”上的 Between (string "start") (many anyChar) (string "end") ,但它也不起作用:

unexpected " "
expecting "end"

我尝试过的另一件事是这个,这当然不适用于任何噪音:

(string "start") *> (many anyChar) <* (string "end")

但它也不起作用:

Prelude Control.Applicative Text.Parsec P> let betw = (string "start") *> (many anyChar) <* (string "end")
Prelude Control.Applicative Text.Parsec P> test betw "start match end"
Left (line 1, column 16):
unexpected end of input
expecting "end"

经过几十年的实验,我开始尝试诸如此类的事情

manyTill anyChar (string "start") on "noise start match end"

unexpected " "
expecting "start"

最佳答案

我同意您可能希望采取更高级别方法的评论。

尽管如此,可以使用秒差距以这种方式解决它,而且您已经快成功了。使用 manyTill 可以,但一开始还无法匹配噪音。所以使用它两次:

GHCi> let test = manyTill anyChar (string "start") *> manyTill anyChar (string "end")
GHCi> parseTest test "foo start match end"
" match "

但是仍然存在一个问题:

GHCi> parseTest test "noise start match end"
parse error at (line 1, column 5):
unexpected "e"
expecting "tart"

Parsec 默认情况下不会回溯,因此看到 noise 中的 s 会使 Parsec 期望 start 的其余部分。为了防止这种情况,您必须对两个“分隔符”使用 try:

GHCi> let test = manyTill anyChar (try $ string "start") *> manyTill anyChar (try $ string "end")
GHCi> parseTest test "noise start match end"
" match "

关于regex - Haskell 中使用 parsec 或 attoparsec 的两个字符串之间的非贪婪匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784412/

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