问题描述
有一段文字:
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 语法是错误的,但我不知道如何改进它,谁能给我一些帮助?
解决方法
您的 Literal
规则接受带引号的字符串,您可以做的是在解析 id 时匹配所有内容直到找到 }
,当您解析类型时匹配所有内容直到看到 { {1}},当您解析描述时,您会匹配所有内容,直到看到 ]
,而在解析标题时,您会匹配所有内容,直到您看到 )
,然后您的规则 .
将产生结果你想要。
Element