Python正则表达式就地查找和替换
我有一个代码片段可以找到像1.321234123这样的浮点数。我想去掉一些精度,并从中得到1.3212。但是我如何访问找到的匹配项、转换它并替换它呢 Python源代码:Python正则表达式就地查找和替换,python,regex,Python,Regex,我有一个代码片段可以找到像1.321234123这样的浮点数。我想去掉一些精度,并从中得到1.3212。但是我如何访问找到的匹配项、转换它并替换它呢 Python源代码: import fileinput import re myfile = open("inputRegex.txt", "r") for line in myfile: line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundVa
import fileinput
import re
myfile = open("inputRegex.txt", "r")
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundValue", line.rstrip())
print(line)
4.2abc -4.5 abc - 1.321234123 abc + .1e10 abc . abc 1.01e-2 abc
1.01e-.2 abc 123 abc .123
输入文件:
import fileinput
import re
myfile = open("inputRegex.txt", "r")
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundValue", line.rstrip())
print(line)
4.2abc -4.5 abc - 1.321234123 abc + .1e10 abc . abc 1.01e-2 abc
1.01e-.2 abc 123 abc .123
使用,inplace=True
。打印行将用作每行的替换字符串
myfile = fileinput.FileInput("inputRegex.txt", inplace=True)
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
"foundValue",
line.rstrip())
print(line)
更新
re.sub
可以接受函数作为替换。它将被match对象调用,函数的返回值用作替换字符串
以下是稍微修改的版本,以使用捕获的组(用于替换功能)
我希望这就是你要找的
num_decimal_places = 2
re.sub(r"(\d+)(\.\d{1,num_decimal_places})\d*", r"\1\2", line.rstrip())
\1\2
捕获两组括号中的匹配项。这不会四舍五入,但会截断输入文件不包含像1.321234123这样的数字。很好!我已经更改了它。但是“foundValue”是一个占位符,我想表示实际的匹配项,我想编辑它。@user1767754,我相应地更新了答案。请检查。@user1767754,是否要将1e-10
替换为0.0000
,将1e10
替换为1000000000.0000
?