替换字符串C#

时间:2017-06-28 14:51:51

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

我的字符串看起来像:

  

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

我想用{/ 1>标记<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>");
}

仅替换第一次出现,如何替换所有出现的?

4 个答案:

答案 0 :(得分:2)

您可以使用正则表达式:

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

答案 1 :(得分:1)

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

你可以在这样的循环中完成这个:

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

答案 2 :(得分:1)

我的变体:

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

因为一个捕获组就足够了

答案 3 :(得分:-2)

使用此正则表达式模式:

\<(.*?)\>

并替换为:

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

导入C#Regex lib并使用匹配和替换方法来执行此操作。