我有一个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等人。在
为什么不只是
regex好像想用大锤打死苍蝇
错误是因为regex中的
?
导致紧靠前面的项变为可选项,但是这里没有前面的项;要避免这种行为,需要用反斜杠转义?
。类似地,=*
将匹配零个或多个=
s,而不是一个=
后面跟着任何东西,这将是=.*
。因此,为了得到你想要的,你需要使用:引用自http://docs.python.org/2/library/re.html#regular-expression-syntax
因此,您需要用反斜杠转义
?
输出
^{pr2}$相关问题 更多 >
编程相关推荐