文字列が一致した正確な位置を見つける必要があります..
>>> pattern = 'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.group()
'Testworld1'
パターン .*1 に一致した 'Testworld1' 文字列から 1 (10 バイト目) の位置が必要です。
やりたいことは2つ。最初に からグループを作成し.*1
、次にグループにアクセスするときに次のように呼び出すことができます.start()
。
>>> pattern = 'Test.*(1)'
>>> match = re.search(pattern,str1)
>>> match.group(1)
'1'
>>> match.start(1)
9
どうですかend()
>>> pattern = r'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.end()
10
より複雑なアプリケーション (マッチの最後の文字の最後の位置を探しているだけではない場合) では、start
代わりにキャプチャを使用したい場合があります。
>>> pattern = r'Test.*(11)'
>>> str1='Testworld11'
>>> match = re.search(pattern,str1)
>>> match.start(1) + 1
10
ここでstart(n)
、th グループのキャプチャの開始インデックスを示します。ここで、n
グループは左かっこによって左から右に数えられます。