我应该如何使用正则表达式来搜索和替换网址中的特殊字符?

问题描述 投票:0回答:2

假设我有一个网址=“https://google.com/?q=cats”,那我该怎么搜索“://”和“?”并用空格替换它们?

import re
url="https://google.com/?q=cats"
re.search("\w+",url) # what should I include in this pattern to detect (:// and ?)
regex python-2.7
2个回答
2
投票

这应该排除你:

re.sub('://|\?', ' ', url)
#https google.com/ q=cats

2
投票
>>> re.sub(r'(://|\?)', ' ', url)
'https google.com/ q=cats'
© www.soinside.com 2019 - 2024. All rights reserved.