【问题标题】:Remove words from string c#从字符串c#中删除单词
【发布时间】:2018-10-11 20:13:59
【问题描述】:

我正在开发一个 ASP.NET 4.0 Web 应用程序,它的主要目标是转到 MyURL 变量中的 URL,然后从上到下读取它,搜索所有以“描述”开头的行" 并且仅在删除所有 HTML 标记时保留这些标记。我接下来要做的是从结果后缀中删除“描述”文本,这样我就只剩下我的设备名称了。我该怎么做?

protected void parseButton_Click(object sender, EventArgs e)
    {
        MyURL = deviceCombo.Text;
        WebRequest objRequest = HttpWebRequest.Create(MyURL);
        objRequest.Credentials = CredentialCache.DefaultCredentials;
        using (StreamReader objReader = new StreamReader(objRequest.GetResponse().GetResponseStream()))
        {
            originalText.Text = objReader.ReadToEnd();
        }

        //Read all lines of file
        String[] crString = { "<BR>&nbsp;" };
        String[] aLines = originalText.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);

        String noHtml = String.Empty;

        for (int x = 0; x < aLines.Length; x++)
        {
            if (aLines[x].Contains(filterCombo.SelectedValue))
            {
                noHtml += (RemoveHTML(aLines[x]) + "\r\n");

            }
        }
        //Print results to textbox
        resultsBox.Text = String.Join(Environment.NewLine, noHtml);
    }
    public static string RemoveHTML(string text)
    {
        text = text.Replace("&nbsp;", " ").Replace("<br>", "\n");
        var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
        return oRegEx.Replace(text, string.Empty);
    }

【问题讨论】:

  • 我会将(编译的)正则表达式存储在静态变量中,这可能会加快进程并避免内存泄漏和 \n 与 Environment.NewLine

标签: c# asp.net string


【解决方案1】:

好的,所以我想出了如何通过我现有的功能之一删除单词:

public static string RemoveHTML(string text)
{
    text = text.Replace("&nbsp;", " ").Replace("<br>", "\n").Replace("description", "").Replace("INFRA:CORE:", "")
        .Replace("RESERVED", "")
        .Replace(":", "")
        .Replace(";", "")
        .Replace("-0/3/0", "");
        var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
        return oRegEx.Replace(text, string.Empty);
}

【讨论】:

    【解决方案2】:
    public static void Main(String[] args)
    {
        string str = "He is driving a red car.";
    
        Console.WriteLine(str.Replace("red", "").Replace("  ", " "));
    }   
    

    输出: 他正在开车。

    注意:在第二个中将其替换为双空格。

    链接:https://i.stack.imgur.com/rbluf.png

    试试这个。它将删除所有出现的要删除的单词。

    【讨论】:

    • 字符串“RED”、“Red”、“reddit”或“transferred”会发生什么?
    • 什么也没发生。它们仍然是“RED”、“Red”、“reddit”
    【解决方案3】:

    使用 LINQ 尝试类似的操作:

    List<string> lines = new List<string>{
    "Hello world",
    "Description: foo",
    "Garbage:baz",
    "description purple"};
    
     //now add all your lines from your html doc.
     if (aLines[x].Contains(filterCombo.SelectedValue))
     {
           lines.Add(RemoveHTML(aLines[x]) + "\r\n");
     }
    
    var myDescriptions = lines.Where(x=>x.ToLower().BeginsWith("description"))
                              .Select(x=> x.ToLower().Replace("description",string.Empty)
                                           .Trim());
    
    // you now have "foo" and "purple", and anything else.
    

    您可能需要针对冒号等进行调整。

    【讨论】:

    • error CS1061: 'string' 不包含'ToLowerCase' 的定义,并且找不到接受'string' 类型的第一个参数的扩展方法'ToLowerCase'(您是否缺少 using 指令或程序集参考?)
    • 还有什么是最好的地方,因为我首先使用“描述”作为过滤器。
    • @KPS 使用 ToLower() 而不是 ToLowerCase()
    【解决方案4】:
    void Main()
    {
        string test = "<html>wowzers description: none <div>description:a1fj391</div></html>";
        IEnumerable<string> results = getDescriptions(test);
        foreach (string result in results)
        {
            Console.WriteLine(result);  
        }
    
        //result: none
        //        a1fj391
    }
    
    static Regex MyRegex = new Regex(
          "description:\\s*(?<value>[\\d\\w]+)",
        RegexOptions.Compiled);
    
    IEnumerable<string> getDescriptions(string html)
    {
        foreach(Match match in MyRegex.Matches(html))
        {
            yield return match.Groups["value"].Value;
        }
    }
    

    【讨论】:

      【解决方案5】:

      Adapted From Code Project

      string value = "ABC - UPDATED";
      int index = value.IndexOf(" - UPDATED");
      if (index != -1)
      {
          value = value.Remove(index);
      }
      

      如果没有- UPDATED,它将打印ABC

      【讨论】:

      • 小心这样做,因为 Remove 将删除从索引到字符串末尾的所有字符。正则表达式或替换只会执行特定的单词/字符。
      猜你喜欢
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2017-03-27
      • 2017-07-17
      • 2014-02-26
      相关资源
      最近更新 更多