【问题标题】:Alternating replace of substrings交替替换子串
【发布时间】:2012-04-18 01:41:31
【问题描述】:

我想知道是否有任何方法可以替换字符串中的子字符串,但可以在字符串之间交替替换它们。即,匹配所有出现的字符串"**",并将第一个出现替换为"<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"

【问题讨论】:

  • 您可以在循环中使用带有起始索引的IndexOf
  • @CodeInChaos 我并没有真正经常使用IndexOf,会看看它,但你有什么实现方法吗?

标签: c# string substring markdown


【解决方案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**这样的字符串)。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 答案过于简单。请提供一个尚未提供的代码示例。
    【解决方案3】:

    试试看

    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>");
    

    干杯,

    【讨论】:

    • 这显然不符合他的要求。
    • 如果空格不存在,这会搞砸,而且没有理由应该这样做。
    • 这适用于我指定的输入,但如果**'s 的起始组位于字符串的开头,则有问题
    【解决方案4】:

    最简单的方法是为**(content)** 使用正则表达式,而不仅仅是**。然后将其替换为 &lt;strong&gt;(content)&lt;/strong&gt; 即可。

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

    【讨论】:

    • 这是最干净的方法,+1。
    • 我看过 MarkDownSharp 但我只想要输入的粗体,而不是整个功能。当它被更频繁地请求时,我可能会开始使用它
    【解决方案5】:

    您可以使用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>";
                }
            });
        }
    }
    

    【讨论】:

    • @Paolo 我刚刚再次使用它并意识到如果将if 语句替换为return index % 2 == 1 ? "&lt;strong&gt;" : "&lt;/strong&gt;"; ,代码可以缩短并且看起来更好一些
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多