如果正規表示式中一個字串出現在另一個字串之前,如何停止搜尋

如果正規表示式中一個字串出現在另一個字串之前,如何停止搜尋

我是正規表示式的新手,尤其是高級正規表示式(向後看或向前看),

我有兩條線,

  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

示範

相關內容