2014-10-10 70 views
0

我想匹配方括號內的數據時間,我認爲前綴「\」將編碼方括號的方式,但它不工作。這裏是我的代碼:Python的正則表達式匹配方括號isse

import re 

line_nginx = re.compile(r"""\[(?P<time_local>\S+) -700\]""", re.IGNORECASE) 

match = line_nginx.match("[07/Oct/2014:19:43:08 -0700]") 
if match: 
    print("matched") 
else: 
    print("no match") 

我得到了「不匹配」。任何想法出了什麼問題?

回答

2
\[(?P<time_local>\S+)\s+-0700\] 

嘗試this.You有0700而不是700。還有在你的正則表達式添加\s+,而不是空間,使其不那麼脆弱。

查看演示。

http://regex101.com/r/xT7yD8/5

2

改變你的正則表達式,

\[(?P<time_local>\S+) -0700\] 

OR

\[(?P<time_local>\S+)\s+-0700\] 

這不是逃避與啓動或關閉方括號的問題。您未能在號碼7之前添加0,因此您的正則表達式不匹配輸入字符串。

>>> import re 
>>> line_nginx = re.compile(r"\[(?P<time_local>\S+)\s+-0700\]", re.IGNORECASE) 
>>> match = line_nginx.match("[07/Oct/2014:19:43:08 -0700]") 
>>> if match: 
...  print("matched") 
... else: 
...  print("no match") 
... 
matched