# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"/assets(/[^\s/?&#]+)+"
test_str = ("\n"
"-1\n"
"down vote\n"
"favorite\n"
"I need to search thru a sql file and find the filename (the end of the url) where the url contains /assets/\n\n"
"Example url:\n\n"
"https://www.example.com/assets/screenshots/this-is-an-example/2016-12-20_15-42-29.png\n\n"
"It has /assets/ in it, so I want to get the last part of the url, being:\n\n"
"2016-12-20_15-42-29.png\n\n"
"Another example:\n\n"
"https://www.example.com/images/screenshots/this-is-an-example/2016-12-20_15-42-29.png\n\n"
"Nothing would return because /assets/ was not found.\n\n"
"*The number of directories deep it goes will be different, so it could be /assets/dir1/dir2/filename.jpg, and the next could be /assets/dir1/dir2/dir3/dir4/filename.jpg\n\n"
"Hoping this can be accomplished using regular expression")
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