How to modify this regular expression to not match a non-breaking space?

Viewed 1624

I'm using John Gruber's regular expression to try to match URLs in a document.

I've represented the regular expression in Python like this:

URL_PATTERN = re.compile(ur'(?i)\b((?:https?://)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))')

This is a modified version of a version found here.

This works well in most cases except for documents which contain non-breaking spaces. In Python I see this represented as \xc2\xa0.

Here is an example string that I'm attempting to parse; hopefully the characters will paste in tact:

Go to https://example.com to log in.

If I print just that string in Python, I get:

In [100]: string
Out[100]: 'Go to\xc3\x82\xc2\xa0https://example.com\xc3\x82\xc2\xa0to log in.'
In [101]: URL_PATTERN.search(string).groups()
Out[102]: ('https://example.com\xc3\x82\xc2\xa0to', None, None, None, None)

The string that I am attempting to match against is an str, not unicode.

How can I modify this regular expression to not match this character? I've tried putting \xc2\xa0 into the ^ negated character class near the end of the regex, but it still matches the URL with the space characters.

1 Answers
Related