Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python脚本中使用正则表达式_Python_Regex_Search_Replace - Fatal编程技术网

在Python脚本中使用正则表达式

在Python脚本中使用正则表达式,python,regex,search,replace,Python,Regex,Search,Replace,我正在尝试编写python脚本来搜索和替换此行: 剩余时间3总计 用空行 这是我的剧本: import glob read_files = glob.glob("*.agr") with open("out.txt", "w") as outfile: for f in read_files: with open(f, "r") as infile: outfil

我正在尝试编写python脚本来搜索和替换此行:

剩余时间3总计 用空行

这是我的剧本:

import glob


read_files = glob.glob("*.agr")

with open("out.txt", "w") as outfile:
    for f in read_files:
        with open(f, "r") as infile:
            outfile.write(infile.read())

with open("out.txt", "r") as file:
    filedata = file.read()
filedata = filedata.replace(r'#time\s+residue\s+[0-9]\s+Total', 'x')
with open("out.txt", "w") as file:
    file.write(filedata)
使用这个,我无法得到任何更换。为什么会这样?代码的其余部分工作正常。输出文件没有更改,因此我怀疑找不到图案


谢谢。

str.replace方法替换固定的子字符串。如果要替换正则表达式模式的匹配项,请使用
re.sub

import re
filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)

str.replace
方法替换固定的子字符串。如果要替换正则表达式模式的匹配项,请使用
re.sub

import re
filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)

非常感谢。这成功了!非常感谢。这成功了!