PDA

View Full Version : [SNIPPET] Revisited between function



Zyt3x
05-15-2014, 12:48 AM
function between(const s1, s2, str : String; mode : (Normal, Inverted, LastFound, FlipFlop) = Normal): String; overload;
var
s1Pos := pos(s1, str);
s2Pos := posEx(s2, str, s1Pos+length(s1));
tmpStr : String;
I : Integer;
begin
case mode of
Normal:
for I := s1Pos+length(s1) to s2Pos-1 do
result := result + str[I];
Inverted:
begin
for I := length(str) downto 1 do
tmpStr := tmpStr + str[I];
tmpStr := between(s1, s2, tmpStr, Normal);
for I := length(tmpStr) downto 1 do
result := result + tmpStr[I];
end;
LastFound:
begin
while posEx(s1, str, s1Pos+length(s1)) > s1Pos do
s1Pos := posEx(s1, str, s1Pos+length(s1));
while posEx(s2, str, s2Pos+length(s2)) > s2Pos do
s2Pos := posEx(s2, str, s2Pos+length(s2));
for I := s1Pos+length(s1) to s2Pos-1 do
result := result + str[I];
end;
FlipFlop:
begin
while posEx(s2, str, s2Pos+length(s2)) > s2Pos do
s2Pos := posEx(s2, str, s2Pos+length(s2));
for I := s1Pos+length(s1) to s2Pos-1 do
result := result + str[I];
end;
end;
end;

var
str := 'C:\System32\someFile.ini, C:\System32\someOtherFile.ini';
s1 := 'C';
s2 := '.';

begin
writeLn('''' + between(s1, s2, str, Normal) + '''');
writeLn('''' + between(s1, s2, str, Inverted) + '''');
writeLn('''' + between(s1, s2, str, LastFound) + '''');
writeLn('''' + between(s1, s2, str, FlipFlop) + '''');
end.

Result:

Compiled successfully in 172 ms.
':\System32\someFile'
'ini, '
':\System32\someOtherFile'
':\System32\someFile.ini, C:\System32\someOtherFile'
Successfully executed.

Modes explained:
Normal will search for the first found s1 and s2 and output what's between those two strings.
Inverted will invert the input string and then search for the first found s1 and s2 and output what's between those two strings.
LastFound will search for the last found s1 and s2 and output what's between those two strings.
FlipFlop will search for the first found s1 and last found s2 and output what's between those two strings.

Besides searching in filepaths, it is also useful when reading json or html or similar languages:
var
str := '<code>stuff!</code>';
s1 := '<';
s2 := '>';

begin
writeLn('''' + between(s1, s2, str, Normal) + '''');
writeLn('''' + between(s1, s2, str, Inverted) + '''');
writeLn('''' + between(s1, s2, str, LastFound) + '''');
writeLn('''' + between(s1, s2, str, FlipFlop) + '''');
end.

Result:

Compiled successfully in 156 ms.
'code'
'stuff!'
'/code'
'code>stuff!</code'
Successfully executed.


Didn't think this simple piece of code would turn out as a wall of text, but I guess I got carried away when showing what it could be used for. :p
Please post here if you find any bugs.