Registriert seit: 16. Feb 2015
Ort: Halle/S.
116 Beiträge
Delphi 10.2 Tokyo Enterprise
|
AW: String analysieren und Textteil ersetzen
6. Jun 2016, 19:24
Rein aus Spaß mal eine Umsetzung mit Regulären Ausdrücken und TDictionary:
Delphi-Quellcode:
uses
System.SysUtils, RegularExpressions, System.Generics.Collections;
type
THashtagReplacer = class
strict private
FDic: TDictionary<string, string>;
function InternalReplaceHashtag(const Match: TMatch): string;
public
constructor Create;
destructor Destroy;override;
procedure AddKeyValue(const Key, Value: string);
function DoReplace(const Input: string): string;
end;
{ THashtagReplacer }
procedure THashtagReplacer.AddKeyValue(const Key, Value: string);
begin
FDic.Add(Key, Value);
end;
constructor THashtagReplacer.Create;
begin
inherited;
FDic := TDictionary<string,string>.Create;
end;
destructor THashtagReplacer.Destroy;
begin
FDic.Free;
inherited;
end;
function THashtagReplacer.DoReplace(const Input: string): string;
begin
Result := TRegex.Replace(Input, '#[^#]+#', InternalReplaceHashtag);
end;
function THashtagReplacer.InternalReplaceHashtag(const Match: TMatch): string;
begin
if not FDic.TryGetValue(Match.Value, Result) then
Result := Match.Value;
end;
Aufruf wäre dann z.B. so
Delphi-Quellcode:
var
TestString: string;
Replacer: THashtagReplacer;
begin
TestString := '#test1# Hallo Welt #test2##test3#';
Replacer := THashtagReplacer.Create;
try
Replacer.AddKeyValue('#test1#', 'foo');
Replacer.AddKeyValue('#test2#', 'bar');
TestString := Replacer.DoReplace(TestString);
WriteLn(TestString); //-> foo Hallo Welt bar#test3#
ReadLn;
finally
Replacer.Free;
end;
end.
Sebastian
|
|
Zitat
|