如何使用fparsec测试2个字符的正确性? [英] How do I test for exactly 2 characters with fparsec?

查看:55
本文介绍了如何使用fparsec测试2个字符的正确性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了以下程序.它需要一行文本并将其分为两部分,第一部分是标识符,第二部分是该行的其余部分.我的标识符(factID)解析器将任何字符串作为标识符,而不是(完全)我想要的.我想要的是一个仅在遇到两个连续的大写字母时才能成功的解析器.因此,例如,"AA"应该成功,而"A","A1"或"AAA"应该不会成功.

I have the following program that runs. It takes a line of text and splits it into two parts, the first is an identifier and the second is the remainder of the line. My parser for the identifier (factID) takes any string of characters as the identifier, which is not (quite) what I want. What I want is a parser that only succeeds when it encounters two consecutive upper case letters. So for example "AA" should succeed while "A", "A1" or "AAA" should not.

我不知道的是如何构造一个查找固定长度令牌的解析器.我以为CharParsers.next2CharsSatisfy可能是我想要的功能,但我不知道如何正确使用它.

What I can't figure out is how construct a parser that looks for a fixed length token. I thought perhaps CharParsers.next2CharsSatisfy might be the function I am looking for, but I can't figure out how to properly use it.

open FParsec

let test p str =
    match run p str with
    | Success(result, _, _)   -> printfn "Success: %A" result
    | Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg

let ws = spaces
let str_ws s = pstring s .>> ws

type StringConstant = StringConstant of string * string

let factID =
    let isIdentifierFirstChar c = isLetter c 
    let isIdentifierChar c = isLetter c 

    many1Satisfy2L isIdentifierFirstChar isIdentifierChar "factID"

let factText =
    let isG c = isLetter c || isDigit c || c = ' ' || c = '.'
    manySatisfy isG 


let factParse = pipe3 factID (str_ws " ") factText
                        (fun id _ str -> StringConstant(id, str))


[<EntryPoint>]
let main argv = 
    test factParse "AA This is some text."      // This should pass
    test factParse "A1 This is some text."      // This should fail
    test factParse "AAA This is some text."     // This passes but I want it to fail
    0 // return an integer exit code

推荐答案

我认为这样做会

let pFactID = manyMinMaxSatisfy 2 2 Char.IsUpper

这篇关于如何使用fparsec测试2个字符的正确性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆