我需要检查字符串是否符合以下规则:http://www.w3.org/TR/widgets/#zip-rel-path
Zip-rel-path = [locale-folder] *folder-name file-name /
[locale-folder] 1*folder-name
locale-folder = %x6C %x6F %x63 %x61 %x6C %x65 %x73
"/" lang-tag "/"
folder-name = file-name "/"
file-name = 1*allowed-char
allowed-char = safe-char / zip-UTF8-char
zip-UTF8-char = UTF8-2 / UTF8-3 / UTF8-4
safe-char = ALPHA / DIGIT / SP / "$" / "%" /
"'" / "-" / "_" / "@" / "~" /
"(" / ")" / "&" / "+" / "," /
"=" / "[" / "]" / "."
UTF8-2 = %xC2-DF UTF8-tail
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
%xF4 %x80-8F 2( UTF8-tail )
UTF8-tail = %x80-BF
lang-tag = primary-subtag *( "-" subtag )
primary-subtag = 1*8low-alphasubtag = 1*8(alphanum)
alphanum = low-alpha / DIGITlow-alpha = %x61-7a
完全符合上述规则的代码示例会有所帮助,我不熟悉 ABNF。 我不需要一种解析 ABNF 的方法,我只需要由习惯或理解 ABNF 的人手动将上述规则翻译为带有正则表达式或任何其他方式的 python 代码。实际上,只需输入一个字符串并最终根据上述规则进行验证,作为输入字符串并在规则匹配或不匹配时返回 true 或 false 的函数。所以用问题的形式来表达:这在 python 中实现起来会是什么样子?
我从 UTF8 文档中看到,上述规则的大部分内容只是检查字符串是否为 utf8: https://www.rfc-editor.org/rfc/rfc3629
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
UTF8-1 = %x00-7F
UTF8-2 = %xC2-DF UTF8-tail
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
%xF4 %x80-8F 2( UTF8-tail )
UTF8-tail = %x80-BF
最佳答案
你应该尝试 pyparsing 。这是quick example来自 pyparsing 网站,您可以轻松修改该网站以满足您的目的。
关于python - 如何使用 python 检查字符串是否符合某些特定的 ABNF 规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041439/