5

I was wondering if there is any way that I can replace substrings within a string but alternate between the string to replace them with. I.E, match all occurences of the string "**" and replace the first occurence with "<strong>" and the next occurence with "</strong>" (And then repeat that pattern).

The input would be something like this: "This is a sentence with **multiple** strong tags which will be **strong** upon output"

And the output returned would be: "This is a sentence with <strong>multiple</strong> strong tags which will be <strong>strong</strong> upon output"

4

5 回答 5

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>";
            }
        });
    }
}
于 2012-04-04T10:52:00.147 回答
1

最简单的方法是实际正则表达式,**(content)**而不仅仅是**. 然后你用它替换它<strong>(content)</strong>,你就完成了。

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

于 2012-04-04T10:52:08.587 回答
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**)。

于 2012-04-04T10:54:29.860 回答
-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>");

干杯,

于 2012-04-04T10:53:11.750 回答
-3

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

于 2012-04-04T10:54:15.493 回答