2012-04-04 78 views
5

我想知道是否有任何方法可以替换字符串中的子字符串,但替换它们之间的替换字符串。 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"

+2

您可以在循环中将'IndexOf'与开始索引一起使用。 – CodesInChaos 2012-04-04 10:49:50

+0

@CodeInChaos我没有真正使用IndexOf,经常会看看它,但你会有任何实现方法? – JakeJ 2012-04-04 10:51:18

回答

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>"; 
      } 
     }); 
    } 
} 
+0

现货。 +1。 – SkonJeet 2012-04-04 10:53:27

+0

@Paolo我只是再次使用它,并意识到如果用'return index%2 == 1替换'if'语句,代码可以缩短并看起来好一点? “”:“”;' – JakeJ 2012-05-01 10:10:51

1

的最简单的方法是实际应用**(content)**而不是**。然后你用<strong>(content)</strong>代替,就完成了。

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

+0

这是最干净的方法,+1。 – 2012-04-04 10:55:33

+0

我看过MarkDownSharp,但我只想输入粗体,而不是整个特征。我可能会开始使用它,当它被要求更频繁 – JakeJ 2012-04-04 10:59:26

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

欢呼声,

+0

,显然不符合他的规范。 – CodesInChaos 2012-04-04 10:54:27

+0

如果空间不存在,这会搞砸,而且没有理由他们应该这样做。 – 2012-04-04 10:55:55

+1

这适用于我指定的输入,但如果'**'的起始组位于字符串的起始位置,则存在问题 – JakeJ 2012-04-04 10:57:52

-3

我认为你应该使用正则表达式匹配的模式,并取代它,它很容易。

+0

答案太简单了。请提供尚未提供的代码示例。 – vapcguy 2016-10-27 18:45:59

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**)。