[Answered ]-How to parse through string containing url changing them to proper links

1๐Ÿ‘

โœ…

>>> test = "This is my sample test blah blah http://t.co/pE6JSwG, hello all"

>>> re.sub('http://[^ ,]*', lambda t: "<a href='%s'>%s</a>" % (t.group(0), t.group(0)), test)

>>> This is my sample test blah blah <a href='http://t.co/pE6JSwG'>http://t.co/pE6JSwG</a>, hello all

This only works if you consider characters like the comma and space a valid stopping point for your url.

In general you should probably not use regexes for url matching, since there may not be a good way to know when a URL ends. If you are guaranteed to have a string with the same format every time, this solution will work. You may also always get URLs of the same length, in which case you can look for the http and collect the substring of that length afterward.

๐Ÿ‘คBrent Newey

1๐Ÿ‘

Perhaps you could get inspiration from the source code of the django-oembed project.

๐Ÿ‘คmntnoe

Leave a comment