python 请编写用于匹配URL的正则表达式
时间: 2023-07-18 22:32:59 浏览: 58
好的,以下是一个简单的用于匹配URL的正则表达式:
```
import re
url_regex = re.compile(
r'^(?:http|ftp)s?://' # scheme
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or IP
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE
)
```
这个正则表达式可以匹配大多数常见的URL格式,包括http、https、ftp等协议,以及IP地址和域名等形式。
相关问题
python 请编写用于匹配URL的正则表达式,并进行判断
好的,以下是一个简单的用于匹配URL的正则表达式,并进行判断的示例代码:
```python
import re
url_regex = re.compile(
r'^(?:http|ftp)s?://' # scheme
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or IP
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE
)
url = input("请输入一个URL: ")
if url_regex.match(url):
print("这是一个合法的URL。")
else:
print("这不是一个合法的URL。")
```
你可以输入一个URL,程序会用正则表达式进行匹配,并输出判断结果。
python正则表达式爬网页
以下是Python正则表达式爬网页的示例代码:
```python
import re
import requests
url = 'https://www.example.com'
response = requests.get(url)
html = response.content.decode('utf-8')
pattern = re.compile('<a href="(.*?)".*?>(.*?)</a>', re.S)
results = re.findall(pattern, html)
for result in results:
link, text = result
print(link, text)
```
在上述示例代码中,我们首先导入了`re`和`requests`模块,然后指定了要爬取的网页URL,并使用`requests.get()`方法获取网页内容。接着,我们使用`response.content.decode('utf-8')`将网页内容转换为UTF-8编码的字符串格式。
接下来,我们使用正则表达式编写了要匹配的模式,该模式可以匹配出网页中所有的超链接。然后,我们使用`re.findall()`方法在网页内容中查找所有符合模式的结果,并将它们存储在`results`变量中。
最后,我们使用一个循环遍历`results`列表,并打印出每个匹配结果中的链接和文本。