fork download
  1. import re
  2. pattern = re.compile( r'''(?xs)
  3. (?<!')(?:'{2})*\B('\b[^'\\]*(?:(?:\\.|\b'\b)[^'\\]*)*') # Single quoted string literal
  4. | # or
  5. (?<!")(?:"{2})*\B("\b[^"\\]*(?:(?:\\.|\b"\b)[^"\\]*)*") # Double quoted string literal
  6. ''')
  7.  
  8. text = "I am \"looking for\" a way that doesn't break: \"Lorem\nipsum\\\" AAAAA\" in this case. Or this AAAAA case. Or this 'AAAAA' case.\nIsn't this annoying?"
  9. print(f"This is the text: {text}")
  10. matches = [f'{x}{y}' for x,y in pattern.findall(text) if 'AAAAA' in f'{x}{y}']
  11. print(matches)
  12.  
  13. ## h ttps://regex 101.com/r/AlFzPT/1/
Success #stdin #stdout 0.03s 9612KB
stdin
Standard input is empty
stdout
This is the text: I am "looking for" a way that doesn't break: "Lorem
ipsum\" AAAAA" in this case. Or this AAAAA case. Or this 'AAAAA' case.
Isn't this annoying?
['"Lorem\nipsum\\" AAAAA"', "'AAAAA'"]