【问题标题】:Replace a pattern inside a string C#替换字符串 C# 中的模式
【发布时间】:2017-06-28 14:51:51
【问题描述】:

我的字符串看起来像:

我的名字是 Jason <and maybe> 我只是看起来像 <a kid> 但我不是

我想用

标记所有看起来像 <bla bla bla> 的东西
<span style='color:red'>bla bla bla></span>

这段代码:

string s = "My name is Jason <and maybe> I just seem like <a kid> but I'm not"; // the string with all the text inside
int start = s.IndexOf("<");
int end = s.IndexOf(">");
if (start >= 0 && end > 0)
{
    string result = s.Substring(start + 1, end - start - 1);
    elem.LayoutText = s.Replace("<" + result + ">" , "<span style='color:red'>" + "<" + result + ">" + "</span>");
}

只替换第一次出现,我怎样才能替换所有?

【问题讨论】:

  • 这是学习正则表达式的好时机。
  • 你需要将你的开始和结束的发现封装在一个数组中,直到它们都返回负数
  • 你想要的结果是什么?

标签: c# .net regex visual-studio visual-studio-2015


【解决方案1】:

您可以使用正则表达式:

string input = "My name is Jason <and maybe> I just seem like <a kid> but I not";
string regexPattern = "(<)([^<>]*)(>)";
string output = Regex.Replace(input, regexPattern, m => "<span style='color:red'>" + m.Groups[2].Value + "</span>");

小提琴:https://dotnetfiddle.net/Jvl0e0

【讨论】:

    【解决方案2】:

    不使用正则表达式,您需要继续在字符串中搜索下一个开始和结束索引。

    您可以像这样在循环中完成此操作:

            string s = "My name is Jason <and maybe> I just seem like <a kid> but I'm not"; // the string with all the text inside
            int start = s.IndexOf("<");
            int end = s.IndexOf(">");
            while (start >= 0 && end > 0)
            {
                string result = s.Substring(start + 1, end - start - 1);
                string rep = "<span style='color:red'>" + "<" + result + ">" + "</span>";
                s = s.Replace("<" + result + ">", rep);
                start = s.IndexOf("<", start +rep.Length + 1);
                end = s.IndexOf(">", end + rep.Length + 1);
            }
             elem.LayoutText = s;
    

    使用正则表达式可以简化这一点:

            string s = "My name is Jason <and maybe> I just seem like <a kid> but I'm not";
            string pattern = "(<)([^<>]*)(>)";
            elem.LayoutText = System.Text.RegularExpressions.Regex.Replace(s, pattern, match => "<span style='color:red'><" + match.Groups[2].Value + "></span>");
    

    【讨论】:

      【解决方案3】:

      我的变种:

      Regex rg = new Regex(@"\<([^<]*)\>");
      Console.WriteLine(rg.Replace("aaez <cde> dfsf <fgh>.", "<span style='color:red'>$1</span>"));
      

      因为一个捕获组就足够了

      【讨论】:

        【解决方案4】:

        使用这个正则表达式模式:

        \<(.*?)\>
        

        并替换为:

        <span style='color:red'>$1</span>
        

        导入 C# 正则表达式库并使用匹配和替换方法来做到这一点。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-04
          • 2011-10-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多