5

我怎样才能得到我需要的字符串的一部分?

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

我想要 email= 之后的数据,但直到 live.com。?

4

6 回答 6

11

有几种方法可以做到这一点。您可以在空格字符上拆分字符串,然后将其输入 TStringList。然后,您可以使用 TStringList 的 Value[String] 属性来获取给定名称的值。

为此,请用逗号替换所有空格:

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

然后将结果导入 TStringList:

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

这将为您提供电子邮件值。然后,您需要在“@”符号处拆分字符串,这是一个相对简单的练习。当然,这只有在空格真的是字段之间的分隔符时才有效。

或者,您可以使用正则表达式,但 Delphi 本身不支持那些(您需要一个正则表达式库 - 请参见此处

*** Smasher 指出 (D2006+) 定界符/定界文本,看起来像这样:

MyStringList.Delimiter := ' ';
MyStringList.DelimitedText := oldString;
Result := MyStringList.Values['email'];
于 2009-10-30T10:58:06.533 回答
2

我的点子:

  1. 用 CRLF 替换空格(它是空格分隔的)
  2. 加载到 TStringList
  3. 使用带有“电子邮件”名称的值属性
于 2009-10-30T10:54:14.387 回答
1

以下代码仅在值不包含空格时才有效:

uses
  StrUtils, Classes;

....

function GetPropertyValue (const PropertyName : String; const InputString : String) : String;
var
  StringList : TStringList;
  Str : String;
begin
Result := '';
StringList := TStringList.Create;
try
  StringList.Delimiter := ' ';
  StringList.DelimitedText := InputString;
  for Str in StringList do
    if StartsText (PropertyName + '=', Str) then
      Result := RightStr (Str, Length (Str) - Length (PropertyName) - 1);    
finally
  FreeAndNil (StringList);
end;
end;
于 2009-10-30T10:48:09.387 回答
1

另一个想法,您也可以将 PosEx (StrUtils) 与 StringList 文本一起使用:

function ExtractMyString(SrcStr, FromStr, ToStr: string): string;
var
  posBeg, posEnd: integer;
begin
  Result := '';
  posBeg := Pos(FromStr, SrcStr) + Length(FromStr);
  posEnd := PosEx(ToStr, SrcStr, posBeg);

  if (posBeg > 0) and (posEnd > posBeg) then
    Result := Copy(SrcStr, posBeg, posEnd-posBeg);
end;

用法:

ExtractMyString(StringList.Text, 'email=', ' lots=');

当然,这仅在源字符串始终以相同方式格式化时才有效,这对于根据需要提取其他数据很方便。

于 2009-10-30T23:40:44.767 回答
1

假设字符串保存在变量 's' 中,而 'tmp' 是另一个字符串变量,

i:= pos ('email=', s);
tmp:= '';
inc (i);
while s[i] <> ' ' do
 begin
  tmp:= tmp + s[i]; 
  inc (i);
 end;

'tmp' 将保存地址

于 2009-11-01T11:23:56.053 回答
0

将字符串拆分为字符串数组,使用“=”作为分隔符,然后您将拥有一个按以下顺序排列的数组:“键”然后“值”,然后您可以循环查找“电子邮件”键,然后简单地将 1 添加到数组索引以获取值。但这可能会以多种方式失败(例如,有人输入 '=' 作为字符)或者值字段中有空字符串

于 2009-10-30T11:02:46.043 回答