使用 FParsec 我将如何解析:以换行符 <|结尾的行>以 eof 结尾的行



我正在解析一个文件,想扔掉我不感兴趣的文件的某些行。 我已经能够让它适用于所有情况,除了最后一行是一次性的并且不以换行符结尾时。

我尝试构建一个endOfInput规则并通过<|>将其与skipLine规则连接。 这一切都包裹在many. 调整所有内容,我似乎要么在不消耗输入的情况下获得许多成功......"错误或skipLine规则失败,当我不尝试某种回溯时。

let skipLine = many (noneOf "n") .>> newline |>> fun x -> [string x]
let endOfInput = many (noneOf "n") .>> eof |>> fun x -> [string x]
test (many (skipLine <|> endOfInput)) "And here is the next.nThen the last."

** 此错误在最后一行的 skipLine 解析器上出现

我试过了

let skipLine = many (noneOf "n") .>>? newline |>> fun x -> [string x]

。和。。。

let skipLine = many (noneOf "n") .>> newline |>> fun x -> [string x]
test (many (attempt skipLine <|> endOfInput)) "And here is the next.nThen the last."

** 这些会产生许多错误

注意:输出函数只是占位符,用于使它们与我的其他规则一起使用。 我还没有弄清楚如何格式化输出。 这是我第一次使用 FParsec,我是 F# 的新手。

FParsec实际上有一个内置的解析器,可以完全按照您的需求进行操作:skipRestOfLine。它终止于换行符或 eof,就像您要查找的内容一样。

如果您想尝试自己实现它作为学习练习,请告诉我,我会尽力帮助您解决问题。但是,如果您只需要一个跳过字符直到行尾的解析器,那么内置skipRestOfLine正是您所需要的。

这是一种使用 Option 类型解析此类文件的方法, 它将帮助您解析末尾带有换行符的文件或跳过中间的空白行。我从那篇帖子中得到了解决方案 - fparsec 键值解析器解析失败.解析一列中具有整数值的文本文件:

module OptionIntParser =
open FParsec
open System
open System.IO

let pCell: Parser<int, unit> = pint32 |>> fun x -> x
let pSome =   pCell |>> Some
let pNone =  (restOfLine false) >>% None
let pLine = (attempt pSome) <|> pNone
let pAllover = sepBy pLine newline  |>> List.choose id
let readFile filePath =
let rr = File.OpenRead(filePath)    
use reader = new IO.StreamReader(rr)    
reader.ReadToEnd()
let testStr = readFile("./test1.txt")
let runAll s  =
let res = run pAllover s in
match res with
| Success (rows, _, _) ->  rows 
| Failure (s, _, _) -> []
let myTest =
let res = runAll testStr
res |> List.iter (fun (x) -> Console.WriteLine(x.ToString() ))

最新更新