import re
mystring = """
# catch this comment
!mycommand
# catch this comment
#catch this comment too
!mycommand
# catch this comment
!mycommand
!mycommand
some code. match until the previous line
# do not catch this comment
!mycommand
# do not catch this comment
"""
import re
m = re.search(r'^(?:\s*(?:#.*|!mycommand\s*))+\s*', mystring)
print(m.group())
aW1wb3J0IHJlCgpteXN0cmluZyA9ICIiIgoKIyBjYXRjaCB0aGlzIGNvbW1lbnQKIW15Y29tbWFuZAojIGNhdGNoIHRoaXMgY29tbWVudAojY2F0Y2ggdGhpcyBjb21tZW50IHRvbwohbXljb21tYW5kCgojIGNhdGNoIHRoaXMgY29tbWVudAohbXljb21tYW5kCiFteWNvbW1hbmQKCnNvbWUgY29kZS4gbWF0Y2ggdW50aWwgdGhlIHByZXZpb3VzIGxpbmUKIyBkbyBub3QgY2F0Y2ggdGhpcyBjb21tZW50CiFteWNvbW1hbmQKIyBkbyBub3QgY2F0Y2ggdGhpcyBjb21tZW50CiIiIgoKaW1wb3J0IHJlCm0gPSByZS5zZWFyY2gocideKD86XHMqKD86Iy4qfCFteWNvbW1hbmRccyopKStccyonLCBteXN0cmluZykKcHJpbnQobS5ncm91cCgpKQo=