使用截断字符串re.sub公司

2024-09-27 07:23:13 发布

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

我有一个url存储为type=str。看起来像这样:

url = 'http://www.dog.com/bone?junk=8dj37hf7'

我要删除所有以“?”开头的字符,所以我会:

^{pr2}$

这就是我尝试过的:

import re
re.sub('?junk=*', '', url)

但我得到一个错误:

raise error, v # invalid expression sre_constants.error: nothing to repeat

解决方法如下:

import re
re.sub('\?junk=.*', '', url)

编辑以插入代码括号。 编辑后添加*符号 Morten Jensen,但错误仍然存在。在

编辑:用“.*”和“\”转义符解决。感谢Morten Jensen,jwodder,thefourtheye等人。在


Tags: importrecomhttpurl编辑wwwtype
3条回答

为什么不只是

url = url.split("?",1)[0]

regex好像想用大锤打死苍蝇

错误是因为regex中的?导致紧靠前面的项变为可选项,但是这里没有前面的项;要避免这种行为,需要用反斜杠转义?。类似地,=*将匹配零个或多个=s,而不是一个=后面跟着任何东西,这将是=.*。因此,为了得到你想要的,你需要使用:

re.sub(r'\?junk=.*', '', url)

引用自http://docs.python.org/2/library/re.html#regular-expression-syntax

'?'

Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.

因此,您需要用反斜杠转义?

url = 'http://www.dog.com/bone?junk=8dj37hf7'
import re
print re.sub('\?.*', '', url)

输出

^{pr2}$

相关问题 更多 >

    热门问题