我有以下peg.js脚本:
start = name*
name = '** name ' var ws 'var:' vr:var ws 'len:' n:num? ws 'label:' lb:label? 'type:' ws t:type? '**\n'
{return {NAME: vr,
LENGTH: n,
LABEL:lb,
TYPE: t
}}
type = 'CHAR'/'NUM'
var = $([a-zA-Z_][a-zA-Z0-9_]*)
label = p:labChar* { return p.join('')}
labChar = [^'"<>|\*\/]
ws = [\\t\\r ]
num = n:[0-9]+ {return n.join('')}
要解析:
** name a1 var:a1 len:9 label:The is the label for a1 type:NUM **
** name a2 var:a2 len: label:The is the label for a2 type:CHAR **
** name a3 var:a3 len:67 label: type: **
,我遇到了两个问题。
首先,在我要解析的文本中,我期望某些值标签,例如“ var:”,“ len:”,“ label:”和“ type:”。据我所知,我想使用这些标签是固定的,以在两个值之间划定界限。
第二,我需要允许缺失的值。
我要采用正确的方法吗?目前,我的脚本将标签的值与类型合并,然后在:
处出现错误Line 1, column 64: Expected "type:" or [^'"<>|*/] but "*" found.
此外,我也可以使用文本块吗?我尝试解析:
** name a1 var:a1 len:9 label:The is the label for a1 type:NUM **
** name a2 var:a2 len: label:The is the label for a2 type:CHAR **
randomly created text ()= that I would like to keep
** name b1 var:b1 len:9 label:This is the label for b1 type:NUM **
** name b2 var:b2 len: label:This is the label for b2 type:CHAR **
more text
修改第一行并添加以下内容:
start = (name/random)*
random = r:.+ (!'** name')
{return {RANDOM: r.join('')}}
我追求的最终结果是:
[
[{
"NAME": "a1",
"LENGTH": "9",
"LABEL": "The is the label for a1",
"TYPE": "NUM"
},
{
"NAME": "a2",
"LENGTH": null,
"LABEL": "The is the label for a2",
"TYPE": "CHAR"
},
{"RANDOM":"randomly created text ()= that I would like to keep"}]
[{
"NAME": "b1",
"LENGTH": "9",
"LABEL": "This is the label for b1",
"TYPE": "NUM"
},
{
"NAME": "b2",
"LENGTH": null,
"LABEL": "This is the label for b2",
"TYPE": "CHAR"
},
{"RANDOM":"more text "}]
]
答案 0 :(得分:1)
您将希望使用负前瞻!(ws 'type:')
,否则标签规则将过于贪婪,并且会将所有输入消耗到行尾。
请注意,您可以使用$()
语法而不是{return n.join('')}
来联接元素的文本。
start = name*
name = '** name ' var ws 'var:' vr:var ws 'len:' n:num? ws 'label:' lb:label? ws 'type:' t:type? ws '**' '\n'?
{return {NAME: vr,
LENGTH: n,
LABEL:lb,
TYPE: t
}}
var = $([a-zA-Z_][a-zA-Z0-9_]*)
num = $([0-9]+)
label = $((!(ws 'type:') [^'"<>|\*\/])*)
type = 'CHAR'/'NUM'
ws = [\\t\\r ]
输出:
[
{
"NAME": "a1",
"LENGTH": "9",
"LABEL": "The is the label for a1",
"TYPE": "NUM"
},
{
"NAME": "a2",
"LENGTH": null,
"LABEL": "The is the label for a2",
"TYPE": "CHAR"
},
{
"NAME": "a3",
"LENGTH": "67",
"LABEL": "",
"TYPE": null
}
]
答案 1 :(得分:0)
最后完成以下工作:
random = r: $(!('** name').)+ {return {"RANDOM": r}}
我不确定我是否完全理解语法,但是它可以工作。