I found a function which will extract a word that is between 2 other words and this works well but I would like to extend the function so it scan the entire string that I choose and extract ALL of the words that are between the 2 keywords and not just the first one it comes to. I am guessing I will need 开发者_运维问答to add a loop of some kind but I am new to Delphi so I do not know exactly what I need to do and I could use some help.
Anyway here is the function that I was talking about.
function GetAWord(sentence, word1, word2 : string) : string;
var
n : integer;
begin
n := pos(word1, sentence);
if n = 0 then begin
result := '';
exit;
end;
delete(sentence, 1, n + length(word1) - 1);
n := pos(word2, sentence);
if n = 0 then begin
result := '';
exit;
end;
result := copy(sentence, 1, n - 1);
end;
Thank You, Emily
You may add an additional argument to the function:
function GetAWord(sentence, word1, word2 : string; Index: Integer) : string;
var
N: integer;
begin
repeat
N:= pos(word1, sentence);
if N = 0 then begin
result := '';
exit;
end;
delete(sentence, 1, n + length(word1) - 1);
n := pos(word2, sentence);
if n = 0 then begin
result := '';
exit;
end;
Dec(Index);
if Index < 0 then begin
result := copy(sentence, 1, n - 1);
Exit
end;
delete(sentence, 1, n + length(word2) - 1);
until False;
end;
// test
procedure TForm1.Button1Click(Sender: TObject);
const
S = '115552211666221177722';
begin
ShowMessage(GetAWord(S, '11', '22', 0));
ShowMessage(GetAWord(S, '11', '22', 1));
ShowMessage(GetAWord(S, '11', '22', 2));
ShowMessage(GetAWord(S, '11', '22', 4));
end;
Well you can find all entries in a single function:
procedure ParseSentence(sentence, word1, word2 : string; Strings: TStrings);
var
N: integer;
begin
Strings.Clear;
repeat
N:= pos(word1, sentence);
if N = 0 then exit;
delete(sentence, 1, n + length(word1) - 1);
n := pos(word2, sentence);
if n = 0 then exit;
Strings.Add(copy(sentence, 1, n - 1));
delete(sentence, 1, n + length(word2) - 1);
until False;
end;
procedure TForm1.Button2Click(Sender: TObject);
const
S = '115552211666221177722';
var
SL: TStringList;
begin
SL:= TStringList.Create;
ParseSentence(S, '11', '22', SL);
Memo1.Lines.Assign(SL);
SL.Free;
end;
精彩评论