我需要解析以以下格式运行命令的日志文件:
cmd options < stdin > stdout 2>> stderr
有些命令不使用stdin;有些不使用标准输出
我可以很容易地分开命令;我在写正则表达式时遇到了麻烦,它可以给我其他的部分
我知道如何匹配到单个字符串:
How to match "anything up until this sequence of characters" in a regular expression?
在字符串a或字符串b之前,我不知道如何匹配
也就是说,我希望匹配选项直到<;或>;或2>&燃气轮机;发生
像这样的尝试是行不通的
import re
test = "cmd test1 test2 -c test3 < infile > outfile 2>> err"
optRegex = '.+?(?=>|<|(2>>))'
optRegex = re.compile(optRegex)
stdoutRegex = '>+?(?=>|<|(2>>))'
stdoutRegex = re.compile(stdoutRegex)
# get options
result = optRegex.search(test)
options = result.group()
rest = test[len(options):]
options = options.rstrip()
# get stdout
result = stdoutRegex.search(rest)
stdout = result.group()
rest = rest[len(stdout):]
stdout = stdout.rstrip()
print(options)
print(stdout)
print(rest)
输出:
cmd test1 test2 -c test3
>
infile > outfile 2>> err
事后看来,使用循环和扫描开始字符和结束字符可能更容易,但我对regex解决方案很好奇
谢谢
目前没有回答
相关问题 更多 >
编程相关推荐