在两个字符串之间提取字符串

时间:2012-12-31 09:08:20

标签: delphi delphi-xe2

如何在A& A之间提取randomstring B.例如:

一个randomstring B

3 个答案:

答案 0 :(得分:13)

假设“randomstring”不包含封闭字符串“A”或“B”,您可以使用两次调用pos来提取字符串:

function ExtractBetween(const Value, A, B: string): string;
var
  aPos, bPos: Integer;
begin
  result := '';
  aPos := Pos(A, Value);
  if aPos > 0 then begin
    aPos := aPos + Length(A);
    bPos := PosEx(B, Value, aPos);
    if bPos > 0 then begin
      result := Copy(Value, aPos, bPos - aPos);
    end;
  end;
end;

当找不到A或B时,该函数将返回空字符串。

答案 1 :(得分:3)

另一种方法:

function ExtractTextBetween(const Input, Delim1, Delim2: string): string;
var
  aPos, bPos: Integer;
begin
  result := '';
  aPos := Pos(Delim1, Input);
  if aPos > 0 then begin
    bPos := PosEx(Delim2, Input, aPos + Length(Delim1));
    if bPos > 0 then begin
      result := Copy(Input, aPos + Length(Delim1), bPos - (aPos + Length(Delim1)));
    end;
  end;
end;

Form1.Caption:= ExtractTextBetween('something?lol/\http','something?','/\http');

结果= lol

答案 2 :(得分:3)

回答正则表达式:)

uses RegularExpressions;
...
function ExtractStringBetweenDelims(Input : String; Delim1, Delim2 : String) : String;


var
  Pattern : String;
  RegEx   : TRegEx;
  Match   : TMatch;

begin
 Result := '';
 Pattern := Format('^%s(.*?)%s$', [Delim1, Delim2]);
 RegEx := TRegEx.Create(Pattern);
 Match := RegEx.Match(Input);
 if Match.Success and (Match.Groups.Count > 1) then
  Result := Match.Groups[1].Value;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 ShowMessage(ExtractStringBetweenDelims('aStartThisIsWhatIWantTheEnd', 'aStart', 'TheEnd'));
end;
相关问题