1

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?

2 Answers 2

2
\[(?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

Sign up to request clarification or add additional context in comments.

Comments

2

Change your regex to,

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

OR

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

It's not the problem with escaping the starting or closing square bracket . You failed to add 0 before the number 7, so your regex wouldn't match the input string.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.