Delphi 批量替换文件中的字符串

{-------------------------------------------------------------------------------
过程名:    LoadStrFromFile 从文件中加载字符串
参数:      filename:string;var str:tstrings  1.文件名;2.加载到的字符串列表;
返回值:    result:boolean  返回是否加载成功。

-------------------------------------------------------------------------------}
function TReplaceString.LoadStrFromFile(filename:string;var str:tstrings):boolean;
begin
  try
    if mUtf8 then
      str.LoadFromFile(filename,TEncoding.UTF8)  //,TEncoding.UTF8
    else
      str.LoadFromFile(filename);
    result:=true;
  except
    result:=false;
    fmain.LogMain('LoadStrFromFile fail:'+filename);
  end;
end;
function TReplaceString.replaceStr(oldstr,newstr:string;var str:string):boolean;
begin
  result:=false;
  if(pos(oldstr,str)>0)then
  begin
    str:=StringReplace (str, oldstr,newstr, [rfReplaceAll]); //ShowMessage(StringReplace (aStr, 'a', 'two', [rfReplaceAll, rfIgnoreCase]));
    result:=true;
  end;
end;



{-------------------------------------------------------------------------------
过程名:    replaceMultiStrInFile 根据新旧字符串列表,替换文件中的字符串
参数:      filename:string;oldArr,newArr:tstrings  1.文件名;2.旧字符串列表;3.新字符串列表;
返回值:    result:boolean  返回是否执行过替换。

-------------------------------------------------------------------------------}
function TReplaceString.replaceMultiStrInFile(filename:string;oldArr,newArr:tstrings):boolean;
var
  fileContent:tstrings;
  i:integer;
  oldstr,str:string;
  bReplace:boolean;
begin
  result:=false;
  fileContent:=TStringList.create;
try
  if not LoadStrFromFile(filename,fileContent) then exit;
  if fileContent.Count=0 then exit;
  bReplace:=false;
  str:=fileContent.Text;
  for I := 0 to oldArr.Count-1 do
  begin
    oldstr:=oldArr[i];
    if(replaceStr(oldstr,newArr[i],str))then bReplace:=true;
    if bReplace then fmain.LogMain('replace: str='+oldStr+' in file='+filename);
  end;
  if bReplace then
  begin
    fileContent.Text:=str;
    if mUtf8 then
    begin
      fileContent.SaveToFile(filename,TEncoding.UTF8);
      DelBomFromUtf8File(filename);
    end
    else begin
      fileContent.SaveToFile(filename); //,TEncoding.UTF8
    end;
  end;
finally
  fileContent.Free;
end;
end;

猜你喜欢

转载自blog.csdn.net/byc6352/article/details/105322304
今日推荐