用/斜杠拆分数组

来自我的数组字符串中的调试器我得到了这个


“/ mercedes-benz / 190-class / 1993 /”class =“canonicalLink”data-qstring =“?sub = sedan”> 1993

我希望在每个’/’之后拆分文本并在string []中获取它,这是我的努力

Queue see = new Queue(); //char[] a = {'\n '}; List car_fact_list = new List(); string[] car_detail; foreach (string s in car) { MatchCollection match = Regex.Matches(s, @"<a href=https://stackoverflow.com/questions/9673817/splitting-the-array-with-slash/(.+?)", RegexOptions.IgnoreCase); // Here we check the Match instance. foreach(Match mm in match) { // Finally, we get the Group value and display it. string key = mm.Groups[1].Value; //key.TrimStart('"'); //key.Trim('"'); key.Trim(); **car_detail = Regex.Split(key, "//");**//I tried with strin.Split as well and tried many combination of seperator , see.Enqueue(key); } 

}

在car_detail [0]中,我得到了这个“$ [link]”> $ [title]

从这个字符串 “/ mercedes-benz / 190-class / 1993 /”class =“canonicalLink”data-qstring =“?sub = sedan”> 1993

目前尚不清楚为什么你在这里使用双斜线…

 string[] details = key.Split('/'); 

应该工作正常。 (请注意, 不必在C#中转义正斜杠。)例如:

 using System; class Test { static void Main() { string text = "/mercedes-benz/190-class/1993/"; string[] bits = text.Split('/'); foreach (string bit in bits) { Console.WriteLine("'{0}'", bit); } } } 

输出:

 '' 'mercedes-benz' '190-class' '1993' '' 

空字符串是由前导和斜杠引起的。 如果你想避免这些,你可以使用

 string[] details = key.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); 

笔记:

  • car_facts是C#中一个非常传统的名字。 通常你会有像CarFacts (或者可能只是CarCarInfo等)的东西。 同样, car_fact_list通常是carFactList或类似的东西。

  • 此代码不符合您的预期:

     key.Trim(); 

    字符串在.NET中是不可变的 – 因此Trim()返回对字符串的引用,而不是更改现有字符串的内容。 你可能想要:

     key = key.Trim(); 
  • 您当前正在为car_detail分配值但从不使用它。 为什么?

  • 一般来说,使用正则表达式解析HTML是一个非常糟糕的主意。 考虑使用HTML Agility Pack或类似的东西。