如何使用PEG.js匹配无包裹字符串并解析指定格式文本
优化方案
核心修改逻辑是废弃原来要求双引号包裹的Literal规则,根据不同字段的边界特征单独定义匹配规则:
- 标题没有包裹符号,匹配到id的起始符号
{前停止 - 三个带包裹的字段直接匹配包裹符号中间的内容,不需要额外引号
- 新增自动trim处理,过滤字段首尾多余空白
修改后可直接运行的完整PEG.js规则如下:
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.trim(); } Id = "{" id: $([^}]*) "}" { return id.trim(); } Title = title: $([^{]*) { return title.trim(); } Description = "(" description: $([^)]*) ")" { return description.trim(); }
测试输入你提供的示例字符串:this is title. {this is id} [this is type] (this is description)
即可直接输出你要求的目标结构。
内容的提问来源于stack exchange,提问作者MoeCasts
相关产品推荐
相关产品推荐

