最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python中用re.sub实现替换且保留原字符串中named group命名的组的部分值

Python crifan 775浏览 0评论
折腾:
【已解决】用Python处理安卓游戏抓包结果成链接加游戏名的格式
期间,对于字符串:
http://udpdcs.4399sy.com/init_info.php?time=1607061237&flag=364804364fefa8226cf4be09a944694a|None
注:
最后的 |后面的None,理论上也可能是其他的值,比如json等
想要替换成:
http://udpdcs.4399sy.com/init_info.php?time=1607061237&flag=364804364fefa8226cf4be09a944694a|巨刃
其中 巨刃 是此处一个游戏名,是固定的,已有的值
然后去想办法用re.sub实现。
此处纠结在于,需要写成:
"(?P<url>https?[^\|]+)\|(?P<type>\w+)"
且被替换后的结果,要保留前面的named grop,即url的命名的组
re.sub
re — Regular expression operations — Python 3.9.1rc1 documentation
https://docs.python.org/3/library/re.html
Python re.sub Examples
去找了半天后,最后是参考自己的帖子
re.sub crifan
【整理】详解Python中re.sub – 在路上
去写成:
            if curAppName:
                replaceP = "\g<url>|%s" % curAppName # '\\g<url>|巨刃'
                replacedUrl = re.sub("(?P<url>https?[^\|]+)\|(?P<type>\w+)", replaceP, eachLine)
即可实现:
# 'http://udpdcs.4399sy.com/init_info.php?time=1607061237&flag=364804364fefa8226cf4be09a944694a|None'
# ->
# 'http://udpdcs.4399sy.com/init_info.php?time=1607061237&flag=364804364fefa8226cf4be09a944694a|巨刃'
实现了要的效果。

转载请注明:在路上 » 【已解决】Python中用re.sub实现替换且保留原字符串中named group命名的组的部分值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
99 queries in 0.337 seconds, using 23.36MB memory