Search code examples
delphidelphi-2007string-parsing

How can I get an e-mail address out of a string of key=value pairs?


How can I get some part of string that I need?

accountid=xxxxxx type=prem servertime=1256876305 addtime=1185548735 validuntil=1265012019 username=noob directstart=1 protectfiles=0 rsantihack=1 plustrafficmode=1 mirrors= jsconfig=1 email=noob@live.com lots=0 fpoints=6076 ppoints=149 curfiles=38 curspace=3100655714 bodkb=60000000 premkbleft=25000000 ppointrate=116

I want data after email= but up to live.com.?


Solution

  • There are a couple of ways to do this. You could split the string on the space character then feed it into TStringList. You can then use TStringList's Value[String] property to get the value of a given name.

    To do that, do a string replace of all spaces with commas:

    newString := StringReplace(oldString, ' ', ',', [rfReplaceAll]);
    

    Then import the result into a TStringList:

    var
      MyStringList : TStringList;
    begin
      MyStringList := TStringList.Create;
      try
        MyStringList.CommaText := StringReplace(oldString, ' ', ',', [rfReplaceAll]);
        Result := MyStringList.Values['email'];
      finally
        MyStringList.Free;
      end;
    end;
    

    This will give you the email value. You'll then need to split the string at the "@" symbol which is a relatively trivial exercise. Of course, this only works if spaces are genuinely a delimiter between fields.

    Alternatively you could use a regular expression but Delphi doesn't support those natively (you'd need a regex library - see here)

    *** Smasher noted (D2006+) Delimiter / Delimited text which would look something like this:

    MyStringList.Delimiter := ' ';
    MyStringList.DelimitedText := oldString;
    Result := MyStringList.Values['email'];