我不想重复
the Cthulhu answer
,但我想使用treetop匹配成对的打开和关闭HTML标记。使用
this grammar
,我可以匹配开始标记和结束标记,但现在我需要一个规则将它们捆绑在一起。我尝试过以下方法,但是使用它可以让我的解析器永远运行下去(无限循环):
rule html_tag_pair
html_open_tag (!html_close_tag (html_tag_pair / '' / text / newline /
whitespace))+ html_close_tag <HTMLTagPair>
end
我试图基于递归圆括号示例和负的前瞻性示例
on the Treetop Github page
. 我引用的其他规则如下:
rule newline
[\n\r] {
def content
:newline
end
}
end
rule tab
"\t" {
def content
:tab
end
}
end
rule whitespace
(newline / tab / [\s]) {
def content
:whitespace
end
}
end
rule text
[^<]+ {
def content
[:text, text_value]
end
}
end
rule html_open_tag
"<" html_tag_name attribute_list ">" <HTMLOpenTag>
end
rule html_empty_tag
"<" html_tag_name attribute_list whitespace* "/>" <HTMLEmptyTag>
end
rule html_close_tag
"</" html_tag_name ">" <HTMLCloseTag>
end
rule html_tag_name
[A-Za-z0-9]+ {
def content
text_value
end
}
end
rule attribute_list
attribute* {
def content
elements.inject({}){ |hash, e| hash.merge(e.content) }
end
}
end
rule attribute
whitespace+ html_tag_name "=" quoted_value {
def content
{elements[1].content => elements[3].content}
end
}
end
rule quoted_value
('"' [^"]* '"' / "'" [^']* "'") {
def content
elements[1].text_value
end
}
end
我知道我需要允许匹配单独的开始或结束标记,但是如果有一对HTML标记存在,我想把它们成对地放在一起。通过将它们与我的语法相匹配来做到这一点似乎是最干净的,但也许有更好的方法?