我可以为下一次输入保存正则表达式状态吗?

Can I save regex state for next input?

我用一些数据解析TCP数据包,这些数据可以分成几个数据包。我无法保存数据包,所以在通过第一个数据包后我无法再次读取它。我需要知道数据中是否存在我的模式,例如,第一个数据包包含 "hello wo",第二个数据包包含 "rld!",我想知道序列中是否存在 "world"。

举个简单的例子,我有两个文件,我可以在其中搜索:

-- file: Seq.hs
import Text.Regex.TDFA
import System.Environment

main = do
    args <- getArgs
    inpStr1 <- readFile (args !! 0)
    putStrLn $ show (inpStr1 =~ "foo" :: Bool)
    inpStr2 <- readFile (args !! 1)
    putStrLn $ show (inpStr2 =~ "foo" :: Bool)

我可以在处理inpStr1 后保存FA 的状态以继续用inpStr2 搜索吗?

我建议您使用 attoparsec. It's fast, robust and allows incremental input:

而不是正则表达式

A fast parser combinator library, aimed particularly at dealing efficiently with network protocols and complicated text/binary file formats.

正则表达式很容易变得丑陋,特别是在 Haskell 中,使用类型化组合器解析库会使事情变得更加清晰。

还有包network-attoparsec:

Utility functions for running a parser against a socket, without the need of a bigger framework such as Pipes or Conduit.