将变量添加到re.search的Python结果并替换(Add variable to the result of re.search Python and replace)

编程入门 行业动态 更新时间:2024-10-27 01:26:17
变量添加到re.search的Python结果并替换(Add variable to the result of re.search Python and replace)

我试图在特定字符之后和特定字符之前找到一个整数,然后为其添加一个整数。

我有这个。

import re filedata = None with open('doc.txt', 'r') as file : filedata = file.read() count = int(filedata.count('~')) # 454 m = re.search('~RR\*(\d+)\*', filedata); print(m) with open('docresult.txt', 'w') as file: file.write(filedata)</pre>

所以我必须完成的任务是在~RR\* XXX *之间加上数字,并将其替换。

所以,如果在一开始我有~RR*120*和我的计数是50我希望新文件说~RR*170*

我也尝试过使用re.compile但没有结果。

I'm trying to find an integer after certain characters and before certain characters, and add an integer to that.

I have this.

import re filedata = None with open('doc.txt', 'r') as file : filedata = file.read() count = int(filedata.count('~')) # 454 m = re.search('~RR\*(\d+)\*', filedata); print(m) with open('docresult.txt', 'w') as file: file.write(filedata)</pre>

So what I have to accomplish is add count to whatever digits are between ~RR\* XXX * and replace it.

So if at the beginning I had ~RR*120* and my count is 50 I want the new file to say ~RR*170*

I tried also with re.compile but had no results.

最满意答案

不确定你的计算(例如,120 + 50如何能够产生175),但是当它们与你的奇怪的~RR*<a number>* pattern使用re.sub 替换函数相匹配时,对你的整数进行计算的替换字符串。

替换函数在与匹配对象匹配时作为唯一参数调用。 它必须返回替换字符串。

import re global count count = 50 filedata = "hello ~RR*120* foo ~RR*40*" def repl_function(m): return str(int(m.group(1))+count+len(m.group(1))) filedata = re.sub('(?<=~RR\*)(\d+)(?=\*)', repl_function, filedata) print(filedata)

该独立示例打印:

hello ~RR*173* foo ~RR*92*

我们看到这些数字已经被提取,计算并以原始字符串替换。 我使用了非消费(lookbehind / lookahead)组,因此只有数字被传递给替换字符串,并且包装模式保存在更新后的字符串中。

Not sure about your computations (how 120+50 can yield 175 for instance), but here's a way to perform computations on your integers when they match your strange ~RR*<a number>* pattern using re.sub with a replacement function instead of a replacement string.

The replacement function is called on a match with the match object as sole parameter. It must return the replacement string.

import re global count count = 50 filedata = "hello ~RR*120* foo ~RR*40*" def repl_function(m): return str(int(m.group(1))+count+len(m.group(1))) filedata = re.sub('(?<=~RR\*)(\d+)(?=\*)', repl_function, filedata) print(filedata)

that stand-alone example prints:

hello ~RR*173* foo ~RR*92*

We see that the numbers have been extracted, computed, and replaced back in the original string. I have used non-consuming (lookbehind/lookahead) groups so only the digits are passed to the replacement string, and the wrapping pattern is kept in the updated string.

更多推荐

本文发布于:2023-07-22 19:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Python   search   Add   result

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!