// extractfen.pas
(*
Detects and prints all FEN strings found in standard input.
./extractfen < "Mate en Dos.pgn" > 155078mi2.fen
*)
uses
SysUtils, RegExpr;
const
{
Regular expressions for the six fields of a FEN string.
https://kirill-kryukov.com/chess/doc/fen.html
}
P = '[1-8BKNPQRbknpqr]+'; // Piece placement (for one rank)
A = '[wb]'; // Active color
C = '([KQkq]+|\-)'; // Castling availability
E = '([a-h][36]|\-)'; // En passant target square
H = '\d+'; // Halfmove clock
F = '[1-9]\d*'; // Fullmove number
var
LLine: string;
LExpr: TRegExpr;
LPattern: string;
begin
LPattern := Format('%s/%s/%s/%s/%s/%s/%s/%s', [P, P, P, P, P, P, P, P]);
LPattern := Format('%s %s %s %s %s %s', [LPattern, A, C, E, H, F]);
LExpr := TRegExpr.Create(LPattern);
while not Eof do
begin
ReadLn(LLine);
if (Length(LLine) > 0) and LExpr.Exec(LLine) then
WriteLn(LExpr.Match[0]);
end;
LExpr.Free;
end.