import re
regex = re.compile(r"^\s*#([\p{Pc}\p{N}\p{L}\p{Mn}]{1,50})$", flags=re.UNICODE | re.MULTILINE)
test_str = ("#validhashtag\n"
"#valid_hashtag\n"
" #validhashtag_with_space_before_or_after\n"
"#valid_hashtag_chars_öÖäÄüÜß\n\n"
"ipsum#notvalid //Not valid: Connected to Word\n"
"http://google.com/#results //Not valid: Same as above\n"
"#not-valid\n"
"#not!valid")
subst = ""
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html