我正在尝试在Python中编写正则表达式,其中一个涉及的字符是\001字符。将\001放入字符串中似乎不起作用。我还尝试过使用'string' + str(chr(1)),但正则表达式似乎无法捕获它。求求大家帮帮我,我已经为此苦苦挣扎了一整天。
import sys
import postgresql
import re
if len(sys.argv) != 2:
print("usage: FixToDb <fix log file>")
else:
f = open(sys.argv[1], 'r')
timeExp = re.compile(r'(\d{2}):(\d{2}):(\d{2})\.(\d{6}) (\S)')
tagExp = re.compile('(\\d+)=(\\S*)\001')
for line in f:
#parse the time
m = timeExp.match(line)
print(m.group(1) + ':' + m.group(2) + ':' + m.group(3) + '.' + m.group(4) + ' ' + m.group(5));
tagPairs = re.findall('\\d+=\\S*\001', line)
for t in tagPairs:
tagPairMatch = tagExp.match(t)
print ("tag = " + tagPairMatch.group(1) + ", value = " + tagPairMatch.group(2))
这是一个输入行的示例。我将'\001'字符替换为'~'以增加可读性。
15:32:36.357227 R 1 0 0 0 8=FIX.4.2~9=0067~35=A~52=20120713-19:32:36~34=1~49=PD~56=P~98=0~108=30~10=134
输出:
15:32:36.357227 R 标签 = 8,值 = FIX.4.29=006735=A52=20120713-19:32:3634=149=PD56=P98=0108=3010=134
因此,它不会在'\001'字符处停止。
timeExp
中,将整个时间表达式捕获在一组括号中是否更容易,这样您就不必重新构建时间表达式(print(m.group(1) + ':' ...
)了吗? - Sam Mussmann'\\'
)。 - Steven Rumbalski