• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

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

date: 2024-01-19 excerpt: 否定的先読みアサーションについて

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


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

概要

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

例

例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: は
"""


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