更新时间:2023-02-17 21:29:55
您可能想使用 Regex.Replace
的重载,该重载接受计算替代的委托:
You probably want to use the overload of Regex.Replace
, that accepts a delegate that computes the replacement:
private string GetCodeForTex(Match match)
{
string tex = match.Groups[1].Value;
return string.Format(
"<img src=\"{0}\" alt=\"{1}\" />", GetEscapedUrlForTex(tex), tex);
}
…
Regex.Replace(textWithDollars, @"\$([^\$]*)\$", GetCodeForTex);
您在 GetCodeForTex
中的代码可能有所不同(您可能会想到一个更好的名称),但是我敢肯定您的想法.
Your code in GetCodeForTex
might be different (and you might think of a better name for it), but I'm sure you get the idea.
此外,请谨慎使用此类正则表达式进行简单解析.这意味着除了封装TeX之外,您永远不能将 $
用作其他用途.如果在输入文本中的某个地方未闭合 $
,结果将很混乱.
Also, be careful with simple parsing using regexes like this. It means you can never use $
for anything else than enclosing TeX. And the result will be mess if you have unclosed $
somewhere in the input text.