超能力:仅当字符串开始一行时才将字符串与解析器匹配 [英] Superpower: match a string with parser only if it begins a line

查看:33
本文介绍了超能力:仅当字符串开始一行时才将字符串与解析器匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超能力解析时,如何只匹配一行中的第一个字符串?

When parsing in superpower, how to match a string only if it is the first thing in a line?

例如,我需要匹配 "A: Hello Goodbye\n" 中的 A 冒号,而不是 "Goodbye A: Hello\n" 中的冒号

For example, I need to match the A colon in "A: Hello Goodbye\n" but not in "Goodbye A: Hello\n"

推荐答案

使用您的示例 此处,我会将您的 ActorParserNodeParser 定义更改为:

Using your example here, I would change your ActorParser and NodeParser definitions to this:

public readonly static TokenListParser<Tokens, Node> ActorParser =
    from name in NameParser
    from colon in Token.EqualTo(Tokens.Colon)
    from text in TextParser
    select new Node {
        Actor = name + colon.ToStringValue(),
        Text = text
    };

public readonly static TokenListParser<Tokens, Node> NodeParser =
    from node in ActorParser.Try()
        .Or(TextParser.Select(text => new Node { Text = text }))
    select node;

我觉得 Superpower 有一个错误,因为我不确定为什么在 NodeParser 中我必须在第一个解析器上放置一个 Try()Or() 链接它,但如果我不添加它会抛出错误.

I feel like there is a bug with Superpower, as I'm not sure why in the NodeParser I had to put a Try() on the first parser when chaining it with an Or(), but it would throw an error if I didn't add it.

此外,您在检查 input[1] 时的验证不正确(可能只是复制粘贴问题).它应该检查 "Goodbye A: Hello" 而不是 "Hello A: Goodbye"

Also, your validation when checking input[1] is incorrect (probably just a copy paste issue). It should be checking against "Goodbye A: Hello" and not "Hello A: Goodbye"

这篇关于超能力:仅当字符串开始一行时才将字符串与解析器匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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