是否可以在python子函数中使用\1匹配器?例如ord("\1"( 我注意到这不起作用:
$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'.-_])","%"+hex(ord("\1")), a)) '
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
而"长度2"非常出乎意料,因为如您所见,它不是2:-
$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'.-_])","(\1)", a)) '
fred(<)was(>)(=)he( )re(,)( )n(=)-3.13e-05(;)(
)
调查它的内容表明函数正在接收文字"\1"而不是替换(0x5C是"\",0x31是"1"(:
$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'.-_])","%"+hex(ord("\1"[0])), a)) '
fred%0x5cwas%0x5c%0x5che%0x5cre%0x5c%0x5cn%0x5c-3.13e-05%0x5c%0x5c
$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'.-_])","%"+hex(ord("\1"[1])), a)) '
fred%0x31was%0x31%0x31he%0x31re%0x31%0x31n%0x31-3.13e-05%0x31%0x31
因此我的问题...我可以使用任何技巧或替代方案将实际占位符放入 ord(( 中?
。
或者:我所处的环境不能依赖 urllib 可用。
底线 - 我正在尝试重现这样的东西:-
$ perl -e '$a="fred<was>=he re, n=-3.13e+05;n"; $a=~s/([^A-Za-z0-9._-])/sprintf("%%%02X", ord($1))/seg; print "$an"'
fred%3Cwas%3E%3Dhe%20re%2C%20n%3D-3.13e%2B05%3B%0A
顺便说一句,请原谅我的提问 - 谷歌的几个小时还没有给出答案,我是 python 的新手,像"\1"这样的搜索词很棘手......
更新:我仍然想知道我最初问题的答案,但与此同时。
a( @JonClements指出 urllib 始终可用(耶!谢谢乔恩(。
b( 我构建了这个丑陋但有效的解决方案:-
import re
a="fred<was>=he re, n=-3.13e+05;rnXxff 0"
b=''
while True:
m = re.search(r"(.*?)([^0-9A-Za-z.-_])(.*)", a, flags=re.S)
if not m:
break
b=b+m.group(1);
b=b+'%'+'%02x' % ord(m.group(2))
a=m.group(3)
a=b+a
print(a)
这给了
fred%3cwas%3e%3dhe%20re%2c%20n%3d-3.13e%2b05%3b%0d%0aX%ff%00
- 警告:不知道 unicode 可能做什么