# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(?<=(?:\s|^)(?![@#])(?!__)\S*)_([^_]+)_"
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"
"match_this_and_that_\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"
"@match_this_and_that_")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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