目录
遇到的问题:
在做爬虫的时候,爬取的url链接内还有转义字符,反斜杠 \\
,打算用正则的re.sub()替换掉的时候遇到了问题,这是要做替换的字符串
最开始直接写
re.sub(\"\\\\\",\"\",item)
编译器漏红了
然后就是找解决办法,最后发现要用四个反斜杠才可以,也就是使用
re.sub(\"\\\\\\\\\",\"\",item)
查了查资料,简单说说我自己的理解。
正则表达式
首先就是正则表达式,对于正则表达式来说,他的语法是独立的,有自己的语法,在正则表达式中,由于反斜杠 \\
是一个特殊字符,可以和其他字母形成转义字符,所以要想表示一个反斜杠 \\
就必须写成 \\\\
这种形式。所以对于正则表达式来说,如果要匹配一个\\
就要写成\\\\
,像这样:
python字符串
在python中,如果想要输出一个反斜杠\\
字符,同样要使用转义:
>>> print(\"\\\\\") \\
同样是因为在python中反斜杠也是一个特殊字符。
综上
当写成
item = \"https:\\/\\/jobs.51job.com/guangzhou-thq\\/137115906.html?s=sou_sou_soulb&t=0_0\" item = re.sub(\"\\\\\\\\\",\"\",item)
首先传入的一个参数是一个字符串,所以python中的字符串解析器会把"\\\\\\\\"
解析成\\\\
,解析之后会再传递给正则表达式的解析器。由于正则表达式也有自己的语法结构,所以当它看到\\\\
时,会把它解析为一个\\
,所以这时候正则匹配就会只匹配一个\\
。
贴一个Stackoverflow上的回答:
If you’re putting this in a string within a program, you may actually
need to use four backslashes (because the string parser will remove
two of them when “de-escaping” it for the string, and then the regex
needs two for an escaped regex backslash).
For instance:
regex("\\\\\\\\")
is interpreted as…
regex("\\\\" [escaped backslash] followed by "\\\\" [escaped backslash])
is interpreted as…
regex(\\\\)
is interpreted as a regex that matches a single backslash.
原文地址:Can’t escape the backslash with regex?
当然还可以使用 raw string来写,也就是写成
re.sub(r\'\\\\\',\'\',item)
由于使用了r'\\\\'
,python的字符串解析器看到r'\\\\'
之后,就直接将外层的r''
去掉然后传递给re解析器,re解析器会再次解析\\\\
为\\
,匹配内容是一个反斜杠\\
字符串方法replace()
除了使用正则替换之外,还可以使用字符串的replace()
str.replace(old, new[, max])
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次
>>> item \'https:\\\\/\\\\/jobs.51job.com/guangzhou-thq\\\\/137115906.html?s=sou_sou_soulb&t=0_0\' >>> item.replace(\'\\\\\',\'\') \'https://jobs.51job.com/guangzhou-thq/137115906.html?s=sou_sou_soulb&t=0_0\' >>>
需要注意的是不论是正则的re.sub()还是str.replace(),使用之后都不会对原始字符串改变:
import re urL =\'https:\\/\\/jobs.51job.com\\/guangzhou-thq\\/137735415.html?s=sou_sou_soulb&t=0_0\' print(urL.replace(\'\\\\\',\'\')) print(urL) print(re.sub(r\'\\\\\',\'\',urL)) print(urL)
暂无评论内容