2009-12-21 4 views
2

내가 정규 표현식을 미리 컴파일 여부에 따라 다른 결과가 무엇입니까 :파이썬 정규 표현식 불일치

>>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean') 
' Bean' 
>>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE) 
'Mr Bean' 

Python documentation기능 중 일부는 컴파일 된 정규 표현식에 대한 완전한 기능을 갖춘 방법의 버전을 단순화라고합니다. 그러나 RegexObject.sub()도 이고 sub() 함수는과 동일합니다.

그래서 여기서 어떻게됩니까?

답변

12

re.sub()re.IGNORECASE을 수락 할 수 없습니다.

문서 상태 :

sub(pattern, repl, string, count=0)

Return the string obtained by replacing the leftmost 
non-overlapping occurrences of the pattern in string by the 
replacement repl. repl can be either a string or a callable; 
if a string, backslash escapes in it are processed. If it is 
a callable, it's passed the match object and must return 
a replacement string to be used.

그러나, 이것은 그 자리에 작동 사용 :

re.sub("(?i)mr", "", "Mr Bean") 
5

모듈 수준의 sub() 호출은 끝에 수정자를 허용하지 않습니다. thats "count"인수 - 교체 될 패턴 발생의 최대 수.

4
>>> help(re.sub) 
    1 Help on function sub in module re: 
    2 
    3 sub(pattern, repl, string, count=0) 
    4  Return the string obtained by replacing the leftmost 
    5  non-overlapping occurrences of the pattern in string by the 
    6  replacement repl. repl can be either a string or a callable; 
    7  if a callable, it's passed the match object and must return 
    8  a replacement string to be used. 

더 기능이 없습니다 매개 변수는 re.compile 같이 정규식 플래그 (IGNORECASE, MULTILINE, DOTALL)의 경우 re.sub입니다.

대안 :

>>> re.sub("[M|m]r", "", "Mr Bean") 
' Bean' 

>>> re.sub("(?i)mr", "", "Mr Bean") 
' Bean' 

편집 파이썬 3.1, http://docs.python.org/3.1/whatsnew/3.1.html 정규식 플래그에 대한 지원을 추가했습니다. 3.1부터는 예를 들어 정규식 모드를 설정하는 플래그를하지 않습니다()

re.sub(pattern, repl, string[, count]) 

의 re.sub : 파이썬 2.6.4 문서에서

re.sub(pattern, repl, string[, count, flags]) 
2

: re.sub는 것 같습니다. re.IGNORECASE를 원하면 re.compile()을 사용해야합니다. sub()