2014-10-10 109 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