【问题标题】:How to parse string without any surround with pegjs?如何用 pegjs 解析没有任何环绕的字符串?
【发布时间】:2021-06-21 19:32:13
【问题描述】:

有一段文字:

this is title. {this is id} [this is type] (this is description)

我要获取关注对象

{
    id: 'this is id',
    title: 'this is title',
    type: 'this is type',
    description: 'this is description',
}

这是我的 pegjs 规则:

start = Text

_ "whitespace"
  = [ \t\n\r]*

Text
    = _ body:Element? _ {
        return {
            type: "Text",
            body: body || [],
        }
    }

Element
    = _ title:Title _ id:Id _ type:Type _ description:Description _ {
        return {
            id: id,
            title: title,
            type: type,
            description: description,
        }
    }

Type
    = "[" type: Literal "]" {
        return type;
    }

Id
    = '{' id: Literal '}' {
        return id;
    }

Title
    = Literal

Description
    = "(" description: Literal ")" {
        return description;
    }

Literal "Literal"
    = '"' char:DoubleStringCharacter* '"' {
        return char.join("");
    }

DoubleStringCharacter
    = !'"' . {
        return text();
    }

还有个问题,不知道怎么匹配没有环绕语法的字符串?

我只知道Literal语法错了,不知道怎么改进,谁能帮帮我?

【问题讨论】:

    标签: pegjs


    【解决方案1】:

    您的 Literal 规则接受带引号的字符串,您可以做的是在解析 id 时匹配所有内容,直到找到 },当您解析类型时匹配所有内容,直到看到 ],当你解析描述匹配所有内容直到你看到),解析标题时匹配所有内容直到你看到.然后你的规则Element将产生你想要的结果。

    start = Text
    
    _ "whitespace"
      = [ \t\n\r]*
    
    Text
        = _ body:Element? _ {
            return {
                type: "Text",
                body: body || [],
            }
        }
    
    Element
        = _ title:Title _ id:Id _ type:Type _ description:Description _ {
            return {
                id: id,
                title: title,
                type: type,
                description: description,
            }
        }
    
    Type
        = "[" type: $[^\]]* "]" {
            return type;
        }
    
    Id
        = '{' id: $[^}]* '}' {
            return id;
        }
    
    Title
        = s:$[^.]* '.' _ {return s}
    
    Description
        = "(" description: $[^)]* ")" {
            return description;
        }
    
    

    【讨论】:

    • 哦,这是工作!但标题规则应该是: ``` Title = s:$[^{]* _ {return s} ``` 我不知道我可以使用 [^] 来匹配字符串。非常感谢你!
    • 感谢您的回馈,我对标题规则的选择纯粹是基于您的示例,当然您可以将其扩展到多个方向:)
    猜你喜欢
    • 2010-10-04
    • 2012-05-04
    • 1970-01-01
    • 2019-04-24
    • 2016-02-21
    • 1970-01-01
    • 2018-03-18
    • 2020-01-30
    • 2020-09-04
    相关资源
    最近更新 更多