正規表現で文字列が別の文字列の前に出現した場合に検索を停止する方法

正規表現で文字列が別の文字列の前に出現した場合に検索を停止する方法

私は正規表現、特に高度な正規表現(後ろを見るか先を見るか)の初心者です。

私には2つのラインがあります。

  1. 赤い袋に入っているボールか、緑の袋に入っているボールを選択します
  2. 緑の袋に入っているボールか、赤い袋に入っているボールを選択します

最初の「バッグ」の前に線が赤である場合にのみ一致させたいと考えました。そして、最初の「バッグ」の後に線が赤である場合は一致させないようにしました(つまり、1 は一致し、2 は一致しません)。

次の正規表現を使用すると、

sort.+?red(?!bag)

または

sort.+?(?!bag)red

どちらの場合も、2 行目に一致するようです。

ヒントや回答があればありがたいです。

答え1

これは役に立ちます:

^(?:(?!\bbag\b).)*\bred\b.+?\bbag\b

説明:

^               # beginning of line
                # tempered greedy token
  (?:           # start non capture group
    (?!         # negative lookahead
      \bbag\b   # "bag" surrounded with word boundary, not matching bags or airbag
    )           # end lookahead
    .           # any character
  )*            # end group, may appear 0 or more times
  \bred\b       # "red" surrounded with word boundary, not matching tired or redition
  .+?           # 1 or more any character, not greedy
  \bbag\b       # "bag" surrounded with word boundary

デモ

関連情報