import re
regex = re.compile(r"http:\/\/example\.com\/foo(\/[\w]+\b)?[^\/]")
test_str = ("http://example.com/foo/apple\n"
"http://example.com/foo/bear\n"
"http://example.com/foo/cake\n\n"
"http://example.com/baa/apple\n"
"http://example.com/foo/apple/cake/bar/1\n"
"http://example.com/foo/bear/camel/bar/2\n\n"
"http://example.com/foo/bear/cake/bar/two\n"
"http://example.com/foo/bear/camel/tar/2\n"
"http://example.com/foo/bear/camel\n"
"http://example.com/foo/bear/camel/\n"
"http://example.com/foo/bear/camel/tar/2/")
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