Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python extracting URLs from a string using regular expressions

Python extracting URLs from a string using regular expressions

Document Object Reference Manual Python3 Examples

Given a string containing URL addresses, we need to use regular expressions to extract the URLs from the string.

Example

import

re

def

Find

(

string

)

:

findall() finds strings matching the regular expression

url

=

re

.

findall

(

'

https?://(?:[-

\w

.]|(?:%[

\d

a-fA-F]{2}))+

'

,

string

)

return

url

string

=

'

Runoob's web address is: https://www.runoob.com, Google's web address is: https://www.google.com

'

print

(

"

Urls:

"

,

Find

(

string

)

)

?: explanation:

(?:x)

matches x but does not remember the match. These parentheses are called non-capturing groups, allowing you to define subexpressions used with regular expression operators. Look at this example /(?:foo){1,2}/. If the expression is /foo{1,2}/, {1,2} would apply only to the last character 'o' of 'foo'. If non-capturing parentheses are used, {1,2} applies to the whole 'foo' word.

The output of the code above is:


Urls:  ['https://www.runoob.com', 'https://www.google.com']

Document Object Reference Manual Python3 Examples