How can i extract randomstring between A & B. For example:
A randomstring B
How can i extract randomstring between A & B. For example:
A randomstring B
Assuming that "randomstring" doesn't contain the enclosing strings "A" or "B", you can use two calls to pos to extract the string:
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;
The function will return an empty string when either A or B are not found.
PosEx comes from StrUtilsAnswer with regular expression :)
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;
RegEx.Another approach:
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');
Result = lol
Str is the name of a built-in procedure and should be avoided for variable names.