简体   繁体   中英

regex that matches all lines that contains a specific word <python>

I would like to match every line that contains the word "Freezer". The catch is everything on that line should match except for the word Freezer. So for example based on our sample data below, the first line should return "Apple" only excluding the keyword Freezer. Same goes with the 3rd and 5th line. I have gone as far as selecting the line by using this regex:

^.*Freezer.*

It selects the 1st, 3rd and 5th lines but couldn't figure out how to exclude "Freezer" on the match.

Apple Freezer   - True
Laptop 15.4" 120GB HD   -   False
Orange Freezer - Banana Mango Left AC   -   True
Prince Yellow Bed   -    False
Grapes Eyes - Fridge/Freezer   - True

Thanks!

This does the job:

regex = r"^.+?(?=Freezer)"

Explanation:

^           : beginning of line
  .+?       : 1 or more any charcter but newline, not greedy
  (?=       : start positive lookahead, zero-length assertion that make sure we have after
    Freezer : literally
  )         : end lookahead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM