我如何在 A 和 B 之间提取随机字符串。例如:
A 随机字符串 B
假设“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 时,该函数将返回一个空字符串。
另一种方法:
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');
结果=哈哈
用正则表达式回答:)
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;