C#替换特定文本而忽略空格

时间:2013-09-10 15:07:09

标签: c# text replace space ignore

我需要在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>"

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

5 个答案:

答案 0 :(得分: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>", "");
}

或 - 因为问题不是很清楚(“必须全部替换为<UL><LI>):

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

答案 1 :(得分:1)

与Regex玩得开心!

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

将第一个参数替换为您需要更改的字符串,如果有&lt; UL&gt;(任何字符,无论它们包括空格)&lt; LI&gt;,它将仅用&lt; UL&gt;替换所有字符;&LT; LI&GT;

答案 2 :(得分:0)

尝试使用Regex:

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

答案 3 :(得分:0)

假设&lt; UL&GT;标签在每个字符串中。

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

答案 4 :(得分:0)

只看这里 String MSDN

还可以使用 String.Replase(string string)

进行重播
相关问题