从字符串中移除单词 C#

9
我正在开发一个ASP.NET 4.0网页应用程序,主要目的是使用MyURL变量中的URL,从上至下读取它,并搜索所有以“description”开头的行,只保留这些行并删除所有HTML标签。接下来我想把结果中的“description”文本删除,只留下我的设备名称。我该如何做?
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);
    }

我会将(已编译的)Regex存储在静态变量中,这可能会加快处理速度并避免内存泄漏和使用 Environment.NewLine 时出现的 \n。 - slfan
5个回答

20

好的,我想出了如何通过我现有的一个函数删除这些单词:

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

6
public static void Main(String[] args)
{
    string str = "He is driving a red car.";

    Console.WriteLine(str.Replace("red", "").Replace("  ", " "));
}   

输出:

他正在开车。

注意:在第二个Replace中有一个双空格。

链接:https://istack.dev59.com/rbluf.webp

试试这个。它将删除所有你想要删除的单词。


3
"RED"、"Red"、"reddit"或"transferred"这些字符串会发生什么? - Jacob Sánchez
什么都没发生。它们仍然是“RED”、“Red”和“reddit”。 - gio

0
尝试使用 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.

你可能需要调整冒号等。


错误 CS1061:'string' 不包含名为 'ToLowerCase' 的定义,也没有接受类型为 'string' 的第一个参数的扩展方法 'ToLowerCase' 可用(是否缺少 using 指令或程序集引用?) - nGX
还有,由于我首先使用“描述”作为过滤器,所以最好的地方是什么? - nGX
@KPS 使用 ToLower() 而不是 ToLowerCase() - shuniar

0

改编自Code Project

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

它将打印ABC,但不包括- UPDATED


小心操作,因为 Remove 方法会删除指定索引到字符串末尾的所有字符。使用正则表达式或 Replace 方法可以只替换特定的单词或字符。 - Micah Montoya

0
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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接