交替替换子串

时间:2012-04-04 10:48:02

标签: c# string substring markdown

我想知道是否有任何方法可以替换字符串中的子字符串,但在字符串之间交替以替换它们。 I.E,匹配字符串"**"的所有出现并用"<strong>"替换第一次出现,用"</strong>"替换下一次出现(然后重复该模式)。

输入将是这样的:"This is a sentence with **multiple** strong tags which will be **strong** upon output"

返回的输出为:"This is a sentence with <strong>multiple</strong> strong tags which will be <strong>strong</strong> upon output"

5 个答案:

答案 0 :(得分:6)

您可以使用Regex.Replace委托的MatchEvaluator重载:

using System.Text.RegularExpressions;

class Program {
    static void Main(string[] args) {
        string toReplace = "This is a sentence with **multiple** strong tags which will be **strong** upon output";
        int index = 0;
        string replaced = Regex.Replace(toReplace, @"\*\*", (m) => {
            index++;
            if (index % 2 == 1) {
                return "<strong>";
            } else {
                return "</strong>";
            }
        });
    }
}

答案 1 :(得分:1)

最简单的方法是**(content)**而不仅仅是**的实际正则表达式。然后,您可以在<strong>(content)</strong>之前将其替换为

您可能还想在https://code.google.com/p/markdownsharp查看MarkdownSharp,因为这确实是您想要使用的内容。

答案 2 :(得分:1)

您可以使用正则表达式来解决此问题:

string sentence = "This is a sentence with **multiple** strong tags which will be **strong** upon output";

var expression = new Regex(@"(\*\*([a-z]+)\*\*)");

string result = expression.Replace(sentence, (m) => string.Concat("<strong>", m.Groups[2].Value, "</strong>"));

此方法将自动处理语法错误(考虑像This **word should be **strong**这样的字符串。)

答案 3 :(得分:-1)

试一试

var sourceString = "This is a sentence with **multiple** strong tags which will be **strong** upon output";
var resultString = sourceString.Replace(" **","<strong>");
resultString = sourceString.Replace("** ","</strong>");

欢呼声,

答案 4 :(得分:-3)

我认为你应该使用正则表达式匹配模式并替换它,这很容易。

相关问题