문제

파이썬에서는 정규 표현식을 컴파일 할 수 있습니다. re.compile:

>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>> 
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>

똑같이 할 수있는 방법이 있지만 사용하지 않고 re.compile. Perl과 같은 것을 찾을 수 없습니다 i 접미사 (예 : m/test/i) 문서에서.

도움이 되었습니까?

해결책

통과하다 re.IGNORECASE ~로 flags 의 매개 변수 search, match, 또는 sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

다른 팁

또한 Ignorecase 플래그없이 검색/매치를 사용하여 Case Insensitive Search를 수행 할 수도 있습니다 (Python 2.7.3에서 테스트) :

re.search(r'(?i)test', 'TeSt').group()    ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group()     ## returns 'TeSt'

사례에 민감한 마커, (?i) REGEX 패턴에 직접 통합 할 수 있습니다.

>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']

패턴 컴파일 중에 둔감 한 경우를 정의 할 수도 있습니다.

pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string. 
#'re.search' returns location of the where the match is found 
#'re.compile' creates a regex object that can be used for multiple matches

 >>> s = r'TeSt'   
 >>> print (re.match(s, r'test123', re.I))
 <_sre.SRE_Match object; span=(0, 4), match='test'>
 # OR
 >>> pattern = re.compile(s, re.I)
 >>> print(pattern.match(r'test123'))
 <_sre.SRE_Match object; span=(0, 4), match='test'>

수입 중

import re

실행 시간 처리 :

RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):

사용하지 않는다고 언급해야합니다 re.compile 낭비합니다. 위의 매치 방법이 호출 될 때마다 정규 표현식이 컴파일됩니다. 이것은 다른 프로그래밍 언어에서도 결함이있는 연습입니다. 아래는 더 나은 연습입니다.

앱 초기화에서 :

self.RE_TEST = re.compile('test', re.IGNORECASE)

실행 시간 처리 :

if self.RE_TEST.match('TeSt'):

사례에 민감하지 않은 작업을 수행하려면 RE.IngoreCase를 공급하십시오

>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']

그리고 우리가 케이스와 일치하는 텍스트를 교체하고 싶다면 ...

>>> def matchcase(word):
        def replace(m):
            text = m.group()
            if text.isupper():
                return word.upper()
            elif text.islower():
                return word.lower()
            elif text[0].isupper():
                return word.capitalize()
            else:
                return word
        return replace

>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top