否定的先読みアサーション

/

否定的先読みアサーションについて

タグ 否定的先読みアサーション


概要

  • (?!) で表現される正規表現
  • マッチしたい文字列に含まれない文字列を指定する

例1

import re

text = "I like oranges and bananas."
pattern = re.compile(r'^(?!.*apple).*')

matches = pattern.finditer(text)
for match in matches:
    print(match.group())
"""
I like oranges and bananas.
"""

例2

import re

# 3つめの"は"はマッチしない
text = "彼は元気です。彼は忙しくはないです。"
pattern = re.compile(r'は(?!ない)')

matches = pattern.finditer(text)
for match in matches:
    print(f"Match at index {match.start()}: {match.group()}")
"""
Match at index 1: は
Match at index 8: は
"""