fork download
  1. import re
  2. text = "Your input string line 1\nLine 2 with fiction\nLine 3 with non-fiction\nLine 4 with fiction and non-fiction"
  3. rx = re.compile(r'\b(?<!non-)fiction\b')
  4. # Approach with regex returning any line containing fiction with no non- prefix:
  5. final_output = [line.strip() for line in text.splitlines() if rx.search(line)]
  6. print(final_output)
  7. # Non-regex approach that does not return lines that may contain non-fiction (if they contain fiction with no non- prefix):
  8. final_output = [line.strip() for line in text.splitlines() if "fiction" in line and "non-fiction" not in line]
  9. print(final_output)
Success #stdin #stdout 0.02s 9620KB
stdin
Standard input is empty
stdout
['Line 2 with fiction', 'Line 4 with fiction and non-fiction']
['Line 2 with fiction']