gpt4 book ai didi

python - 正则表达式/python 查找和替换字符串中的特定数字

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:45 25 4
gpt4 key购买 nike

我需要替换出现在较长字符串中的数字(角),这些字符串看起来都与此类似:

[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]

我的函数需要用一个"new"数字替换一个“旧”数字,例如如果旧数字是 17 而新数字是 19,那么结果应该是:

[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]

请注意,仅应替换\中的数字(也可以是//)。

为此,我尝试设置一个正则表达式替换,目的是避免\\或//之外的数字:newplane = re.compile(r[^[_] ("+ str(oldcorner) + ")").sub(str(newcorner), oldplane)

我很快意识到这行不通,因为正则表达式从行的开头开始搜索,如果不匹配模式就会失败。

一定有一些我不知道的聪明方法。有什么建议吗?

最佳答案

您可以在正则表达式的子部分内使用回调函数:

import re

def callback(match):
return match.group(0).replace('17', '19')

s = "[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]"

s = re.compile(r'\\.+?\\').sub(callback, s)

print s

打印:

[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]

关于python - 正则表达式/python 查找和替换字符串中的特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com