0

我想要做的是采用如下字符串

 This is my string and *this text* should be wrapped with <strong></strong>

结果应该是

这是我的字符串,这个文本应该用

4

3 回答 3

1

这似乎工作得很好:

var str = "This is my string and *this text* should be wrapped with";

var updatedstr = String.Concat(
          Regex.Split(str, @"\*")
          .Select((p, i) => i % 2 == 0 ?  p : 
               string.Concat("<strong>", p, "</strong>"))
          .ToArray()
 );
于 2013-06-05T02:06:39.757 回答
0

那这个呢:

string s = "This is my string and *this text* should be wrapped with <strong></strong>";
int i = 0;
while (s.IndexOf('*') > -1)
{
    string tag = i % 0 == 0 ? "<strong>" : "</strong>";
    s = s.Substring(0, s.indexOf('*')) + tag + s.Substring(s.indexOf('*')+1);
    ++i;
}

或者马蒂华莱士在问题评论中的正则表达式想法,\*[^*]+?\*

于 2013-06-05T01:49:55.550 回答
0

对于这种情况,您可以使用一个非常简单的正则表达式:

var text = "";
text = Regex.Replace(text, @"\*([^*]*)\*", "<b>$1</b>");

请参阅.NET 正则表达式演示。在这里,\*([^*]*)\比赛

  • \*- 一个字面星号(*是一个特殊的正则表达式元字符,需要在字面上转义)
  • ([^*]*)- 第 1 组:除字符外的零个或多个*字符
  • \*- 一个*字符。

替换模式中的$1是指在第 2 组中捕获的值。

演示屏幕

在此处输入图像描述

于 2021-11-19T22:16:02.907 回答