我想在python中編寫正則表達式,其中涉及的字符之一是\ 001字符。把\ 001放在一個字符串中似乎不起作用。我也嘗試過'string'+ str(chr(1)),但是正則表達式似乎沒有捕獲它。請爲了上帝的愛而有人幫助我,我一整天都在爲此而苦苦掙扎。如何在python字符串中放置字符文字
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ř 標籤= 8,值= FIX .4.29 = 006735 = A52 = 20120713-19:32:3634 = 149 = PD56 = P98 = 0108 = 3010 = 134
因此它不會停在'\ 001'字符處。
你應該使用重的 「原始」 的字符串.. 。 – 2012-07-30 18:42:08
在'timeExp'中,在一組圓括號中捕獲整個時間表達式是不是更容易,所以您不必重新構建時間表達式('print(m.group(1)+':'.. .')? – 2012-07-30 18:49:38
@Jon Clements:我認爲Alex沒有使用原始字符串,因爲他想將字符串文字包含在他的模式中。@Alex,如果要避免使用原始字符串以便在模式中使用字符串文字,反斜槓應該是加倍(''\\'')。 – 2012-07-30 18:50:16