如何在没有任何环绕的情况下解析字符串?
How to parse string without any surround with pegjs?
有文字:
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 时,匹配所有内容直到找到 }
,当您解析类型时匹配所有内容直到您看到a ]
,当你解析描述时,你会匹配所有内容,直到你看到 )
,当你解析标题时,你会匹配所有内容,直到你看到 .
,然后你的规则 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;
}
有文字:
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 时,匹配所有内容直到找到 }
,当您解析类型时匹配所有内容直到您看到a ]
,当你解析描述时,你会匹配所有内容,直到你看到 )
,当你解析标题时,你会匹配所有内容,直到你看到 .
,然后你的规则 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;
}