2014-10-10 3 views
0

대괄호 안에 datatime을 맞추려고합니다. 접두사 "\"는 대괄호를 인코딩하는 방법이 될 것이라고 생각했지만 어떻게 든 작동하지 않았습니다. 여기 내 코드는 다음과 같습니다.파이썬 정규식 대괄호 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이 덜 취약한 확인하기 위해 정규식 공간 대신 ​​\s+를 추가 .Also 0700 대신 700을보십시오.

데모보기

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

2

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

또는

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