I don't have time to post a tested solution to your post sharpening the confusing specifications of the OPed problem. Whenever I post untested stuff, there's usually a huge bug right in the middle of it, but anyway...
The solution I posted here can fairly easily be adapted to your expanded, clarified specifications if you can load the entire file into memory at once, i.e., if the file is smaller than, say, a couple hundred MB (assuming your running on a bargain-basement laptop). I'm assuming you know how to "slurp" a file in this way and that it's been slurped into the $s scalar. Then, change the %replacement hash to
my %replacement = (
'b' => 'Black to move',
'w' => 'White to move',
);
and change the s///g substitution to
$s =~ s{
Event \s+ " \K [?] (?= " .*? FEN [^\n]* \s+ ($string2) \s+ -)
}
{$replacement{$1}}xmsg;
This assumes that:
-
There can be any number, including zero, of lines between the Event and FEN lines, or they can be on the same line;
-
FEN is always on the same line as the b/w business (update: but see Update below);
-
Event-FEN-b/w sequences are never nested or interleaved;
-
Event-FEN-b/w all match case-sensitively.
After the s///g substitution, write the modified $s scalar out to a file.
If you know for sure that the mapping in the %replacement hash will never change, you can get rid of the code building the $string2 regex based on the hash and just define the regex as
my $string2 = qr{ \b (?: b | w) \b }xms;
(although I hope you will give it a better name).
Again, this untested code still needs Perl version 5.10+ regex extensions (although it could fairly easily be adapted to an earlier version), and it's untested.
Update: On second thought, it seems to me that there's a possible problem with the \s+ ($string2) \s+ sub-pattern of the
Event \s+ " \K [?] (?= " .*? FEN [^\n]* \s+ ($string2) \s+ -)
regex that I've suggested for the s/// match. The \s class includes newline, so \s+ could match a wild and crazy string like "\t \n\t\n\n \t" that is obviously not all one line as one of the assumptions stated above would have it. It may not make any practical difference, but I think I would rather use something like [ \t]+ in place of \s+ in the problematic sub-pattern, making it [ \t]+ ($string2) [ \t]+ instead. Of course, the all-one-line assumption referred to may not actually be pertinent; in that case, no problem.
Give a man a fish: <%-{-{-{-<
|