import re
regex = re.compile(r"(?:^| )[^@#\s_]*(_([^_\n]+)_)", flags=re.MULTILINE)
test_str = ("Test sentence:\n"
"_some_val #ta_g_ and _some_ value, but some_val_ and #some_tag_value and @a_mention_ and a #_tag_\n\n"
"Should match (between underscores)\n"
"----\n"
"_italic text here_\n"
"police_woman_\n"
"_fire_fighter\n"
"a thousand _words_\n"
"_brunch_ on a Sunday\n\n"
"Should not match anything\n"
"----\n"
"@ta_g_\n"
"__value__\n"
"#some_tag_value\n"
"@some_value_here\n"
"@some_tag_\n"
"#some_val_\n"
"#_hello_\n")
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