正则表达式替换美元符号之间的文本 [英] RegEx to replace text between dollar signs

查看:43
本文介绍了正则表达式替换美元符号之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#.NET替换美元符号之间的每个文本实例.例如:

I would like to use C# .NET to replace every instance of text between dollar signs. For example:

Check out this TeX: $x\in\mathbb{Z}^+$. It's cool.

...成为...

Check out this TeX: <img src="http://chart.googleapis.com/chart?cht=tx&chl=x\in\mathbb{Z}^%2B" alt="x\in\mathbb{Z}^+" />. It's cool.

请注意,在将公式传递到Google Charts API之前,需要对其进行URL编码.

Note that the formula needs to be URL encoded before it is passed to the Google Charts API.

请您告诉我如何使用RegEx(或其他方式)执行此操作吗?

Please could you show me how to do this using RegEx (or otherwise)?

推荐答案

您可能想使用 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.

这篇关于正则表达式替换美元符号之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆