我不想重复the Cthulhu answer,但是我想用Treetop来匹配开始和结束标记对。使用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标记,我希望将它们组合在一起。将它们与我的语法相匹配似乎是最干净的方法,但也许还有更好的方法?
发布于 2012-08-31 08:45:12
您只能对每个HTML标记对使用单独的规则,或者使用语义谓词。也就是说,通过保存开始标记(在sempred中),然后接受(在另一个sempred中)结束标记(如果它是相同的标记)。这在Treetop中要困难得多,因为没有方便的位置来保存上下文,也不能查看解析器堆栈,但这是可能的。
顺便说一句,在解析MIME边界(和Markdown)时也会出现同样的问题。我还没有检查过Mikel在ActionMailer中的实现(可能他使用了一个嵌套的Mime解析器),但在Treetop中是可能的。
在http://github.com/cjheath/activefacts/blob/master/lib/activefacts/cql/parser.rb中,我将上下文保存在一个伪输入流中-您可以看到它必须支持哪些方法-因为" input“在所有SyntaxNodes上都可用。我在那里使用sempreds有不同的原因,但其中一些技术是适用的。
发布于 2012-11-23 02:24:01
这是一个非常简单的语法,它使用语义谓词来匹配结束标记和开始标记。
grammar SimpleXML
rule document
(text / tag)*
end
rule text
[^<]+
end
rule tag
"<" [^>]+ ">" (text / tag)* "</" [^>]+ &{|seq| seq[1].text_value == seq[5].text_value } ">"
end
endhttps://stackoverflow.com/questions/4150860
复制相似问题