我怎么才能得到re.sub公司()忽略模式中的问号?

2024-09-28 19:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个长文件中删除url。 我的代码运行良好,除了这个实例(下面)。 我认为问题是url字符串有一个?。 在我的循环中如何处理这个案子? 我怎么能强迫re.sub公司()忽略?在url变量中?在

blah = 'City of San Jose. Playa to Paseo, http://www.sanjoseca.gov/index.aspx?nid=5876'
url='http://www.sanjoseca.gov/index.aspx?nid=5876'
re.sub(url,'',blah)

OUT>>'City of San Jose. Playa to Paseo, http://www.sanjoseca.gov/index.aspx?nid=5876'

Desired OUT>>> 'City of San Jose. Playa to Paseo, '

编辑:用一个奇怪的字符手动修复整个文件中的每个url 不是我想做的。我在这里用URL循环超过1000行。在


Tags: oftohttpurlcityindexwwwgov
1条回答
网友
1楼 · 发布于 2024-09-28 19:07:37

您需要正确转义正则表达式中的所有特殊字符,以匹配文字字符。这包括期间以及:

blah = 'City of San Jose. Playa to Paseo, http://www.sanjoseca.gov/index.aspx?nid=5876'
url='http://www\.sanjoseca\.gov/index\.aspx\?nid=5876'
print(re.sub(url,'',blah))

或者,您可以使用^{cd1>}为您执行此操作:

^{pr2}$

相关问题 更多 >