2014-01-06 7 views
3

명확성을 위해 정규식을 여러 줄로 나누고 싶지만 원시 문자열을 사용하는 것이 가장 좋은 방법인지 모르겠습니다.파이썬의 원시 문자열에 암시 적 라인 조인에 필요한 내용

SECT_EXP = (
    r'^(?P<number>.+?[.]? {1,2}' # Begin number pattern match 
    r'(?P<sect_num>' # Begin section number match 
    r'(?P<full_num>' # Begin full number match 
    r'(?P<title>\d{1,2}?)' # Match title substring 
    r'(?P<chapter>\d{2})' # Match chapter substring 
    r')' # End full number match 
    r'[.]' 
    r'(?P<section>\d+)' # Match section substring 
    r')' # End section number match 
    r')' # End number pattern match 
    r'([.]?)[ ]*$' # Lazy matching end of strings 
) 

그러나 암시 적 라인 결합을 사용할 때 전체 문자열이 원시 문자열로 처리되도록하려면 각 문자열 앞에 r을 붙여야합니까? this 페이지에서

답변

4

:

re.X 
re.VERBOSE 

이 플래그는 더 좋은 볼 정규 표현식을 작성할 수 있습니다. 문자 클래스에있을 때 또는 이스케이프 처리되지 않은 백 슬래시 앞에있는 경우를 제외하고 패턴 내의 공백은 무시됩니다. 줄에 '#'문자 클래스가 없거나 이스케이프 처리되지 않은 백 슬래시가 있으면 ' '이 무시됩니다. 진수와 일치하는 다음 두 정규 표현식 객체가 기능적으로 동일하다는 것을 의미

:

a = re.compile(r"""\d + # the integral part 
        \. # the decimal point 
        \d * # some fractional digits""", re.X) 

b = re.compile(r"\d+\.\d*") 

당신이 볼 수 있듯이, 'R'로 트리플 인용 문자열을 사용할 수 있습니다 접두어로 사용할 수 있습니다.