簡體   English   中英

查找帶有正則表達式的文本並在文件中替換

[英]Find text with regular expression and replace in file

我想在帶有正則表達式的文件中找到文本,然后將其替換為另一個名稱。 我必須首先逐行讀取文件,因為以其他方式re.match(...)找不到文本。

我想修改的測試文件是(不全部,我刪除了一些代碼):

//...
#include <boost/test/included/unit_test.hpp>
#ifndef FUNCTIONS_TESTSUITE_H
#define FUNCTIONS_TESTSUITE_H
//...
BOOST_AUTO_TEST_SUITE(FunctionsTS)
BOOST_AUTO_TEST_CASE(test)
{
  std::string l_dbConfigDataFileName = "../../Config/configDB.cfg";
  DB::FUNCTIONS::DBConfigData l_dbConfigData;
//...
}
BOOST_AUTO_TEST_SUITE_END()
//...

現在,將configDB名稱替換為另一個的python代碼。 我必須通過正則表達式查找configDB.cfg名稱,因為名稱一直都在變化。 僅名稱,不需要擴展名。

碼:

import fileinput
import re

myfile = "Tset.cpp"

#first search expression - ok. working good find and print configDB
with open(myfile) as f:
  for line in f:
    matchObj = re.match( r'(.*)../Config/(.*).cfg(.*)', line, re.M|re.I)
    if matchObj:
      print "Search : ", matchObj.group(2)

#now replace searched expression to another name - so one more time find and replace - another way - not working - file after run this code is empty?!!!
for line in fileinput.FileInput(myfile, inplace=1):    
    matchObj = re.match( r'(.*)../Config/(.*).cfg(.*)', line, re.M|re.I)
    if matchObj:
      line = line.replace("Config","AnotherConfig")

文檔

可選的就地過濾:如果將關鍵字參數inplace = 1傳遞給fileinput.input()或FileInput構造函數,則文件將移至備份文件,而標准輸出將定向到輸入文件 (如果與備份文件相同的名稱已經存在,將被靜默替換)。

您需要做的只是在循環的每個步驟中打印line 另外,您需要打印的行沒有其他換行符,因此可以從sys模塊使用sys.stdout.write 結果是:

import fileinput
import re
import sys

...
for line in fileinput.FileInput(myfile, inplace=1):    
    matchObj = re.match( r'(.*)../Config/(.*).cfg(.*)', line, re.M|re.I)
    if matchObj:
      line = line.replace("Config","AnotherConfig")
    sys.stdout.write(line)

添加:另外我還假設您需要將config.cfg替換為AnotherConfig.cfg 在這種情況下,您可以執行以下操作:

import fileinput
import re
import sys

myfile = "Tset.cpp"

regx = re.compile(r'(.*?\.\./Config/)(.*?)(\.cfg.*?)')

for line in fileinput.FileInput(myfile, inplace=1):    
    matchObj = regx.match(line, re.M|re.I)
    if matchObj:
        sys.stdout.write(regx.sub(r'\1AnotherConfig\3', line))
    else:
        sys.stdout.write(line)

您可以在此處閱讀有關function sub信息: python docs

如果我了解您,則需要更改以下內容:

std::string l_dbConfigDataFileName = "../../Config/configDB.cfg";

只是將文件名“ configBD”更改為其他文件名,然后重寫該文件。

首先,我建議寫一個新文件並更改文件名,以防出現問題。 如果不存在匹配項,則不使用re.match而是使用re.sub,否則將返回更改后的行,否則將返回未更改的行-只需將其寫入新文件即可。 然后更改文件名-將舊文件更改為.bck,將新文件更改為舊文件名。

import re
import os

regex = re.compile(r'(../config/)(config.*)(.cfg)', re.IGNORECASE)

oldF = 'find_config.cfg'
nwF = 'n_find_config.cfg'
bckF = 'find_confg.cfg.bck'

with open ( oldF, 'r' ) as f, open ( nwF, 'w' ) as nf :
    lns = f.readlines()
    for ln in lns:
        nln = re.sub(regex, r'\1new_config\3', ln )
        nf.write  ( nln )


os.rename ( oldF, bckF )
os.rename ( nwF, oldF )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM