I want to define an environment (in a class file, as it happens) the contents of which are both displayed on-screen as they are written, but they are also modified (e.g. using the l3regex package) and then written to a file.
My specific requirement is that I want a solution environment (in which the answers to a question are given), but the solution has a mark scheme given by a series of \marks{...} commands. The version that is written to file needs to have these \marks{...} parts removed.
The following mwe code, based on this post, correctly carries out the regex replacement that I need in the context required:
\documentclass{article}
\usepackage{l3regex}
\usepackage{environ}
\usepackage{marginnote}
\renewcommand\marks[1]{\marginnote{[#1]}}
\ExplSyntaxOn
\NewEnviron{solution}
{
\strip_marks:V \BODY
}
\tl_new:N \solution_text_tl
\cs_new_protected:Nn \strip_marks:n
{
\tl_set:Nn \solution_text_tl { #1 }
\solution_text_tl % Inserts original text in the right place
\regex_replace_all:nnN { \c{marks}\cB\{ [0-9]* \cE\} } { } \solution_text_tl
\regex_replace_all:nnN { \c{marks} [0-9] } { } \solution_text_tl
\immediate\write\answerfile{\solution_text_tl}
%\solution_text_tl <-- ***Regex done, how to write to file?***
}
\cs_generate_variant:Nn \strip_marks:n { V }
\ExplSyntaxOff
\begin{document}
\newwrite\answerfile
\immediate\openout\answerfile=solution-no-marks.tex
\begin{solution}
This line has a \emph{mark} at the end of it.\marks{10}
\end{solution}
\immediate\closeout\answerfile
\end{document}
As written, this code returns an error (related to marginnote, but really it's because in writing to file, it has expanded the \emph{...}). If I remove the \emph{...} inside the solution environment, then the code compiles as expected. However, I really need to preserve the control sequences inside the solution environment when writing to file. I've tried, e.g., the answers package (or some other solution like this, all relying on verbatim to some extent), but then how do I do the regex replacement that I want?

\iow_now:NVand then use that ? Hard to tell without code to play with. (Well, one of the experts might not need the code, of course.) But I take it that you don't want it completely unexpanded. Or do you really want literally\solution_text_tlwritten to the file? – cfr Apr 17 '16 at 22:19\solution_text_tl(I can do that!), but rather I want to write the \BODY of the environment unexpanded, after carrying out some regex replacement. – rbrignall Apr 17 '16 at 22:30\marks, which is a TeX primitive (to be precise, e-TeX). – egreg Apr 17 '16 at 23:01