【问题标题】:Replace specific text while ignoring spaces忽略空格替换特定文本
【发布时间】:2013-09-14 09:00:50
【问题描述】:

我需要在 C# 中替换文本,同时忽略任何空格。

例如:

"This is a text with some tags <UL> <P> <LI>", 
"This is a text with some tags <UL>   <P>    <LI>", 
"This is a text with some tags <UL><P>    <LI>" or 
"This is a text with some tags <UL><P><LI>"

必须全部替换为

"This is a text with some tags <UL><LI>"

请注意,我不能从整个字符串中删除空格然后替换所需的字符串,因为这会给出错误的结果 -

"Thisisatextwithsometags<UL><LI>"

我确定这3个标签

"<UL>", "<P>" and "<LI>"

将按该顺序出现,但不确定它们之间的空格。

【问题讨论】:

    标签: c# text replace space


    【解决方案1】:

    使用String.Replace:

    string text = "This is a text with some tags <UL>   <P>    <LI>";
    int indexOfUl = text.IndexOf("<UL>");
    if (indexOfUl >= 0)
    {
        text = text.Remove(indexOfUl) + text.Substring(indexOfUl).Replace(" ", "").Replace("<P>","");
    }
    

    旧答案(在您上次编辑之前使用):

    string[] texts = new[]{"<UL> <P> <LI>", "<UL>   <P>    <LI>", "<UL><P>    <LI>" , "<UL><P><LI>"};
    for(int i = 0; i < texts.Length; i++)
    {
        string oldText = texts[i];
        texts[i] = oldText.Replace(" ", "").Replace("<P>", "");
    }
    

    或者——因为问题不是很清楚(“必须全部替换为&lt;UL&gt;&lt;LI&gt;):

    // ...
    texts[i] = "<UL><LI>"; // ;-)
    

    【讨论】:

    • 我事先不确定文本之间会有多少空格。所以它不能放在一个数组中。
    • @user2751130:我不明白你的评论。您提供了几个要修改的示例字符串。我已将这些字符串添加到集合中,以向您展示如何删除空格和&lt;P&gt;-tags。所以空格根本与数组无关。我还可以删除数组并使用三个不同的字符串变量。
    • 嘿@TimSchmelter,OP 添加了详细信息。这个答案不再适用于他的目的。只是想让你知道。
    【解决方案2】:

    享受正则表达式的乐趣!

    Regex.Replace("<UL>   <P>    <LI>", "<UL>.*<LI>", "<UL><LI>", RegexOptions.None);
    

    将第一个参数替换为您需要更改的字符串,如果有

      (任何字符,无论它们包括空格)
    • ,它将全部替换为
      • .

    【讨论】:

      【解决方案3】:

      尝试使用正则表达式:

      Regex.Replace(inputString, "> *<", "><");
      

      【讨论】:

      • -1 这根本不起作用。在他的第一个示例中,结果如下:这是带有一些标签

        • 的文本。他不想留下

          。看我的回答。

      【解决方案4】:

      假设 标签在每个字符串中。

        string[] stringSeparators = new string[] { "<UL>" };
        string yourString = "This is a text with some tags <UL><P><LI>";
        string[] text = yourString.Split(stringSeparators, StringSplitOptions.None);
        string outPut = text [0]+" "+ ("<UL>" + text[1]).Replace(" ", "").Replace("<P>", "");
      

      【讨论】:

        【解决方案5】:

        看看这里String MSDN

        也用于替换使用String.Replace(string string)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-14
          • 2012-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-18
          • 1970-01-01
          相关资源
          最近更新 更多