# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"https?:\/\/(?:w{1,3}\.)?[^\s.]*(?:\.[a-z]+)+(?::\d+)?(?![^<]*(?:<\/\w+>|\/?>))"
test_str = ("This is my text to be parsed which contains url \n"
"http://someurl.com <a href=\"http://thisshouldnotbetampered.com\">\n"
"some text and a url http://someotherurl.com test 1q2w </a> <img src=\"http://someasseturl.com/abc.jpeg\"/>\n\n"
"Hello http://someurl.com</a> <!-- fail -->\n"
"<img src=\"http://someurl.com/image.jpg>\n"
"http://someurl.localhost.com\n"
"<div>Regex is awesome</div>\n\n\n\n"
"<a href='https://help.mojohelpdesk.com/mytickets/show/26737327'>https://help.mojohelpdesk.com/mytickets/show/26737327</a>\n\n"
"<a href=\"https://help.mojohelpdesk.com/mytickets/show/26737327\">https://help.mojohelpdesk.com/mytickets/show/26737327</a>\n\n"
"https://google.com\n\n"
"https://www.mojo.com\n\n\n\n"
"http://localhost:3000\n\n"
"http://site.quelqu\n\n"
"http://localhost.com:3000\n\n"
"www.google.com")
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