How to match the first word after an expression in a string with Pascal

1 Answer

0 votes
program FindNextWord;

function FindNextWord(const text, expression: string): string;
var
  i, index: Integer;
  resultWord: string;
  
begin
  index := Pos(expression, text);
  
  if index > 0 then
  begin
    index := index + Length(expression); // Move past the found expression

    // Skip spaces after the expression
    while (index <= Length(text)) and (text[index] = ' ') do
      Inc(index);

    // Extract the next word
    resultWord := '';
    i := index;
    while (i <= Length(text)) and not (text[i] in [' ', '.', ',', ';', ':']) do
    begin
      resultWord := resultWord + text[i];
      Inc(i);
    end;

    if resultWord <> '' then
      FindNextWord := resultWord
    else
      FindNextWord := 'No word found!';
  end
  else
    FindNextWord := 'No match found!';
end;

var
  text, expression: string;
begin
  text := 'The quick brown fox jumps over the lazy dog.';
  expression := 'fox';

  WriteLn('The first word after "', expression, '" is: ', FindNextWord(text, expression));
end.



(*
run:

The first word after "fox" is: jumps

*)

 



answered Jun 14, 2025 by avibootz
...