fork download
  1. import re
  2.  
  3. s = '''
  4. COMMENTS:
  5. first comment /user_x
  6. second comment
  7. two lines /user_y
  8. Here is some unimportant text.
  9. KEYWORD:
  10. Don't match comments or anything else after first keyword like this /user_x
  11. KEYWORD: <- again
  12. Also ignore same keyword which could appear serveral times.
  13. '''
  14. pattern = re.compile(r'COMMENTS:\s*((?:(?:(?!KEYWORD:).)+?/(?:user_x|user_y))+).+?KEYWORD:', flags=re.DOTALL)
  15. match = re.search(pattern, s)
  16. if match:
  17. print(match.group(1))
  18.  
  19.  
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
first comment /user_x  
second comment
two lines /user_y