import re
regex = re.compile(r"(?<![\p{L}0-9])([##][·・ー_0-90-9a-zA-Za-zA-Zぁ-んァ-ン一-龠]{1,24})(?![\p{L}0-9])", flags=re.UNICODE)
test_str = ("Hashtag must be started with # character.\n"
"Hashtag will be detected by space character and other special characters (!,@,&,*,%,$).\n"
"Example 1: Hello#guys. This is a #test. -> Valid hashtag: #test.\n"
"Example 2: Hello#guys. This is a #test!#message. -> Valid hashtag: #test and #message\n"
"Example 3: Hello#guys. This is a #test #message. -> Valid hashtag: #test and #message\n"
"Example 4: Hello#guys. This is a #test#message. -> Valid hashtag: #test\n"
"Example 5: #asdasdasdasdasdasdasdasdasd -> Valid hashtag: none\n"
"Example 6: # -> Valid hashtag: none\n"
"#日本語#asd => Valid hashtag should be #日本語\n"
"#日本語日本語日本語日本語日本語日本語日本語日本語日本語 => Will not a valid hashtag")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
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