【问题标题】:Remove a defined part from a string从字符串中删除定义的部分
【发布时间】:2014-05-22 09:16:39
【问题描述】:

假设我有这个字符串:

string text = "Hi my name is <crazy> Bob";

我想去掉括号内的所有东西,结果是这样的:

"Hi my name is Bob". 

所以我已经尝试过了,我知道我一直认为 while 循环有误,但我就是想不通。

    public static string Remove(string text)
    {
        char[] result = new char[text.Length];

        for (int i = 0; i < text.Length; i++ )
        {
            if (text[i] == '<')
            {
                while (text[i] != '>')
                {
                    result[i] += text[i];
                }
            }
            else
            {
                result[i] += text[i];
            }
        }
        return result.ToString();
    }

【问题讨论】:

  • 查找正则表达式
  • 输入可以是Hi my name is &lt;crazy&gt; uncle &lt;strange&gt; Bob.吗?是否应该只删除crazystrangeuncle
  • result[i] += text[i]; 内部while(text[i]!='&gt;') 循环更改为i++; 以便能够通过'&lt;''&gt;' 内部的字符并返回new string(result);

标签: c# string char


【解决方案1】:

试试这个正则表达式:

public static string Remove(string text)
{
    return  Regex.Replace(text, "<.*?>","");
}

【讨论】:

  • dang...我的打字速度不够快!
  • 该死 - 比我快 2 秒!
  • 这是一个很好的选择,但它并不能帮助 OP 理解为什么他们尝试的解决方案不起作用。
  • @DaveParsons 虽然你是对的,但当你可以轻松实现它时,我什至懒得去看看哪里出了问题。基本上我很懒:-D
【解决方案2】:

看看这个循环:

while (text[i] != '>')
{
    result[i] += text[i];
}

这将继续执行,直到条件不满足。鉴于你没有改变text[i],它永远不会停止......

此外,您在 char[] 上调用 ToString,这不会做您想做的事情,即使这样做,您也会有剩余的字符。

如果你想像这样循环,我会使用StringBuilder,并记录你是否“在”尖括号中:

public static string RemoveAngleBracketedContent(string text)
{
    var builder = new StringBuilder();
    int depth = 0;
    foreach (var character in text)
    {
        if (character == '<')
        {
            depth++;
        }
        else if (character == '>' && depth > 0)
        {
            depth--;
        }
        else if (depth == 0)
        {
            builder.Append(character);
        }
    }
    return builder.ToString();
}

或者,使用正则表达式。让它处理嵌套的尖括号会相对棘手,但如果你不需要它,它真的很简单:

// You can reuse this every time
private static Regex AngleBracketPattern = new Regex("<[^>]*>");
...

text = AngleBracketPattern.Replace(text, "");

最后一个问题 - 从"Hi my name is &lt;crazy&gt; Bob" 中删除带尖括号的文本后,您实际上得到了"Hi my name is Bob" - 请注意双倍空格。

【讨论】:

  • +1 为 OP 提供了众所周知的钓鱼课和一条鱼!
【解决方案3】:

使用

string text = "Hi my name is <crazy> Bob";
text = System.Text.RegularExpressions.Regex.Replace(text, "<.*?>",string.Empty);

【讨论】:

  • 答案与@Sriram Sakthivel 答案相同
【解决方案4】:

我推荐正则表达式。

public static string DoIt(string content, string from, string to)
{
    string regex = $"(\\{from})(.*)(\\{to})";
    return Regex.Replace(content, regex, "");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2017-07-02
    相关资源
    最近更新 更多