2019-05-07
Python regex match square bracket issue
源自: stackoverflow
问题

I am trying to match a datatime inside square brackets and I thought prefixing "\" would be the way to encode square brackets but somehow it didn't work. Here is my code:

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")

I got "no match". Any idea what went wrong?

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

Try this.You have 0700 instead of 700.Also add \s+instead of space in your regex to make it less fragile.

See demo.

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

Python regex match square bracket issue
查看原网页