re.compile を使用しない場合、大文字と小文字を区別しない正規表現を使用しますか?

StackOverflow https://stackoverflow.com/questions/500864

質問

Python では、次を使用して大文字と小文字を区別しないように正規表現をコンパイルできます。 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.IGNORECASEflags のパラメータ search, match, 、 または sub:

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

他のヒント

また、(Pythonの2.7.3でテスト)IGNORECASEフラグなしで検索/マッチを使って大文字小文字を区別しない検索を行うことができます:

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

大文字と小文字を区別しないマーカー、(?i)は、正規表現パターンに直接組み込むことができます。

>>> 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を使用していないことは無駄であることに言及しなければなりません。上記のmatchメソッドが呼び出されるたびに、正規表現がコンパイルされます。また、これは他のプログラミング言語での不良の練習です。下記より良い練習です。

アプリケーションの初期化の場合:

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

実行時の処理でます:

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

大文字と小文字を区別しない操作を実行するには、供給re.IGNORECASE

>>> 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