Reo*_*orx 5 python regex string-parsing logstash
Logstash的grok是一个基于正则表达式构建的字符串解析工具,它提供了许多模式,使字符串解析工作变得更加容易,我第一次使用它时就爱上了它.但不幸的是,它是用Ruby编写的,因此无法在我的Python项目中使用,所以我想知道是否有任何Python实现的grok,或者是否有任何Python替代方案可以像grok一样简化字符串解析?
我不知道grok的任何python端口,但实现这个功能非常简单:
import re
types = {
'WORD': r'\w+',
'NUMBER': r'\d+',
# todo: extend me
}
def compile(pat):
return re.sub(r'%{(\w+):(\w+)}',
lambda m: "(?P<" + m.group(2) + ">" + types[m.group(1)] + ")", pat)
rr = compile("%{WORD:method} %{NUMBER:bytes} %{NUMBER:duration}")
print re.search(rr, "hello 123 456").groupdict()
# {'duration': '456', 'bytes': '123', 'method': 'hello'}
Run Code Online (Sandbox Code Playgroud)