5

文字列内の部分文字列を置き換えることができるが、それらを置き換えるために文字列を交互に使用できる方法があるかどうか疑問に思いました。IE、文字列のすべての出現を一致させ"**"、最初の出現をで置き換え、次の出現をで置き換え"<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"

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 に答える