Put this in your preamble
% Usage
% \Aftergroup{ balanced text }
% \Aftergroup token text token
% where text is any row of tokens and token is a character that is not in text (compare \verb)
%
% Example:
% \Aftergroup {\aaa{bbb}} and \Aftergroup @\aaa{bbb}@ put \aaa{bbb} after the endgroup
% whereas \Aftergroup }\aaa{bbb}} and \Aftergroup \egroup\aaa{bbb}} put \aaa{bbb after the second "}"
%
% For the unbalanced text a problem is that we can not distinguish "{" and "\bgroup" (or
% "}"and "\egroup". Hence by
% Aftergroup @\bgroup \egroup@ the tokens inserted after the group are "{}" and by
% Aftergroup \bgroup \egroup @\bgroup the tokens "}@ are put after the group.
\makeatletter
\def\Aftergroup{\bgroup
\let\Bgroup={\let\bgroup}%give \bgroup a different meaning, } to balance
\@ifnextchar\Bgroup
{\egroup\@AGBalancedText}
{\@ifnextchar\egroup
{\egroup\def\@AGdelimiter{\egroup}\afterassignment\@AGDelNextToken\let\@let@token=}
{\egroup\@AGDelimited}}
}
\def\@AGDelimited#1{\def\@AGdelimiter{#1}\@AGDelNextToken}
\def\@AGDelNextToken{%
\expandafter\@ifnextchar\@AGdelimiter{\let\@let@token=}%end
{\@ifnextchar\bgroup
{\aftergroup{\iffalse}\fi\afterassignment\@AGDelNextToken\let\@let@token=}
{\@ifnextchar\egroup
{\iffalse{\fi\aftergroup}\afterassignment\@AGDelNextToken\let\@let@token=}
{\@AGDeltoken}
}}}
\def\@AGDeltoken#1{\aftergroup#1\@AGDelNextToken}
\def\@AGBalancedText#1{\@AGBalNextToken#1{\@AGBalNextToken}}
\def\@AGBalNextToken#1#{\@AGBalNotOpen#1\@AGBalNotOpen\@AGBalClose}
\def\@AGBalNotOpen#1{\ifx\@AGBalNotOpen#1\else\aftergroup#1\expandafter\@AGBalNotOpen\fi}
\def\@AGBalClose#1{%
\ifx\@AGBalNextToken#1\relax%
\else\ifx\@AGBalClose#1\relax\iffalse{\else\aftergroup}\fi
\expandafter\expandafter\expandafter\@AGBalNextToken%
\else\iftrue\aftergroup{\else}\fi\@AGBalNextToken#1{\@AGBalClose}%
\fi
\fi
}
\makeatother
The following code
{\Aftergroup }\def\aaa{123}}\relax}\show\aaa
{\Aftergroup {\def\aaa{123\bgroup\egroup}}}\show\aaa
{\Aftergroup @\def\aaa{123\bgroup\egroup}@}\show\aaa
then gives
> \aaa=macro:
->123\relax .
l.102 {\Aftergroup }\def\aaa{123}}\relax}\show\aaa
?
> \aaa=macro:
->123\bgroup \egroup .
l.103 ...p {\def\aaa{123\bgroup\egroup}}}\show\aaa
?
>\aaa=macro:
->123{}.
l.104 ...p @\def\aaa{123\bgroup\egroup}@}\show\aaa
in the output window of TeX.