2012-12-13 2 views
6

파이썬 (2.7)에서 자세한 정규 표현식을 사용하려고합니다. 그것이 중요한 경우 나는 되돌아 가서 더 명확하게 미래의 언젠가를 더 분명하게 이해하도록 노력하고 있습니다. 내가 새로 왔기 때문에 나는 내가 원하는 것을 얻고 있는지 확인하기 위해 컴팩트 한 표현을 처음 만들었다. 여기 파이썬에서 자세한 REGEX 구현하는 방법

컴팩트 식입니다

그것은 여기

을 예상대로 작동
test_verbose_item_pattern = re.compile('\n{1}\b?I[tT][eE][mM]\s+\d{1,2}\.?\(?[a-e]?\)?.*[^0-9]\n{1}') 

가 자세한 정보 표현을하다

verbose_item_pattern = re.compile(""" 
\n{1}  #begin with a new line allow only one new line character 
\b?  #allow for a word boundary the ? allows 0 or 1 word boundaries \nITEM or \n ITEM 
I  # the first word on the line must begin with a capital I 
[tT][eE][mM] #then we need one character from each of the three sets this allows for unknown case 
\s+  # one or more white spaces this does allow for another \n not sure if I should change it 
\d{1,2} # require one or two digits 
\.?  # there could be 0 or 1 periods after the digits 1. or 1 
\(?  # there might be 0 or 1 instance of an open paren 
[a-e]?  # there could be 0 or 1 instance of a letter in the range a-e 
\)?   # there could be 0 or 1 instance of a closing paren 
.*   #any number of unknown characters so we can have words and punctuation 
[^0-9]  # by its placement I am hoping that I am stating that I do not want to allow strings that end with a number and then \n 
\n{1}  #I want to cut it off at the next newline character 
""",re.VERBOSE) 

문제는 내가 자세한 패턴을 실행할 때 내가 얻을 것입니다 예외

Traceback (most recent call last): 
File "C:/Users/Dropbox/directEDGAR-Code-Examples/NewItemIdentifier.py", line 17, in <module> 
""",re.VERBOSE) 
File "C:\Python27\lib\re.py", line 190, in compile 
    return _compile(pattern, flags) 
File "C:\Python27\lib\re.py", line 242, in _compile 
raise error, v # invalid expression 
error: nothing to repeat 

이것은 어리석은 일 이겠지만 두려워하지는 않습니다. 필자는 장황한 표현을 취하여 줄 단위로 압축하여 압축 된 버전이 자세한 내용과 동일한 지 확인했습니다.

반복 할 사항이 없다는 오류 메시지가 표시됩니까?

+0

백 슬래시를 이스케이프 처리해야합니다. 정상적인 파이썬 문자열 처리 단계에서 변환되기 때문에 정규식 엔진으로 변환하지 않습니다. 이 때문에 압축 된 버전에서만 우연히 작동했습니다. 또한 "원시 문자열 리터럴"을 찾으십시오 :-) – Cameron

+0

@Cameron 덕분에 삼중 인용문을 사용했기 때문에 슬래시를 벗어날 필요가 없었습니다. 나는 당신이 말했듯이 패턴이 예기치 않게 끝난다. 나는 백 슬래시를 벗어나 문자열 앞의 r을 사용하지 않은 예제를 보았다. – PyNEwbie

답변

9
  • 이 정규식 패턴을 정의 할 때 원시 문자열 리터럴을 사용하는 좋은 습관이다. 많은 정규 표현식 패턴은 백 슬래시를 사용하며, 원시 문자열 리터럴을 사용하면 대신에 단일 백 슬래시를 쓸 수 있습니다. 파이썬이 백 슬래시를 다른 의미로 해석할지 여부를 걱정해야합니다 (두 개의 백 슬래시 그 경우).

  • \b?은 (는) 잘못된 정규 표현식입니다. 이것은 0 또는 1 단어 경계를 말합니다. 그러나 단어 경계가 있거나 그렇지 않습니다. 단어 경계가있는 경우 1 단어 경계가 있습니다. 단어 경계가 없으면 단어 경계가 0입니다. 따라서 \b? (유효한 정규식 인 경우) 항상 참일 것입니다.

  • 정규식은 문자열의 끝과 줄의 끝을 구별합니다. 문자열은 여러 줄로 구성 될 수 있습니다.

    • \A은 문자열의 시작 부분에만 일치합니다.
    • \Z은 문자열의 끝 부분에만 일치합니다.
    • $은 문자열의 끝과 일치하고 re.MULTILINE 모드의 줄 끝과 일치합니다.
    • ^은 문자열의 시작과 일치하고 re.MULTILINE 모드에서 줄의 시작과도 일치합니다.

import re 
verbose_item_pattern = re.compile(r""" 
    $   # end of line boundary 
    \s{1,2}  # 1-or-2 whitespace character, including the newline 
    I   # a capital I 
    [tT][eE][mM] # one character from each of the three sets this allows for unknown case 
    \s+   # 1-or-more whitespaces INCLUDING newline 
    \d{1,2}  # 1-or-2 digits 
    [.]?   # 0-or-1 literal . 
    \(?   # 0-or-1 literal open paren 
    [a-e]?  # 0-or-1 letter in the range a-e 
    \)?   # 0-or-1 closing paren 
    .*   # any number of unknown characters so we can have words and punctuation 
    [^0-9]  # anything but [0-9] 
    $   # end of line boundary 
    """, re.VERBOSE|re.MULTILINE) 

x = verbose_item_pattern.search(""" 
Item 1.0(a) foo bar 
""") 

print(x) 

수익률

<_sre.SRE_Match object at 0xb76dd020> 

+0

답장을 보내 주셔서 감사합니다. 도움이되었고 유용한 것들을 배웠습니다. 나는 $를 이해하지 못했고, 나는 그것을하지 않고 멀티 라인 플래그를 사용하면 정규식이 작동하지 않는다는 것을 이해하지 못한다. – PyNEwbie

1

으로 당신이 당신의 백 슬래시를 이스케이프하거나 함께 원시 문자열을 사용한다 주석의 말 (일치가 나타내는) 트리플 쿼트.

verbose_item_pattern = re.compile(r""" 
... 
관련 문제