2013-01-03 40 views
-2

我有这个字符串...C#分割特定字符串特定数据

lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64 

字符串总是在变化......

我怎么会得到两个特定点之间的数据...

我真正需要的是提取hd-180-1。和hr-155-61。并将它们从字符串中删除

但是您看到数据始终是hd-180-1。 - 它可能是hd-171-4。 - 所以我需要删除HD和之间的数据。以编程方式

我该如何去做这件事?

+1

您是否尝试过RegEx? –

+0

可能重复的[PHP - 从字符串中删除特定字符串](http://stackoverflow.com/questions/11382611/php-strip-a-specific-string-out-of-a-string) –

+0

一种方法这是非常灵活的,但可能不够高性能的是使用我的[sscanf()替换为.NET](http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net)。它允许你定义占位符并提取你需要的任何部分。 –

回答

1

这看起来像正则表达式

string s = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64"; 

s = Regex.Replace(s, @"hd.*?\.", ""); 
s = Regex.Replace(s, @"hr.*?\.", ""); 
Console.WriteLine(s); 

here's my favorite regex reference

工作你也可以使用正则表达式来匹配你的模式

string s = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64"; 

Regex r = new Regex(@"hd.*?\."); 
Console.WriteLine(r.Match(s).Value); 
0

您可能需要使用IndexOfSubstring(或可能是正则表达式)的组合。你真的需要理解并解释,正好你的字符串是如何构建的,以便提取你想要的数据。

IndexOf搜索字符串。它返回字符串中第一个出现的字母。它也可以在字符串中找到一个子字符串。它通常用于循环构造。当没有发现任何东西时它返回负值。

子串提取字符串。它要求你指出一个开始索引和一个长度。然后,它返回一个字符一个完全新的字符串,在这个范围内

 string data = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64"; 

     int indexOf_hd = data.IndexOf("hd"); 
     int indexOf_fullstop = data.IndexOf(".", indexOf_hd); 

     string extracteddata = data.Substring(indexOf_hd, indexOf_fullstop - indexOf_hd); 

     // extracteddata = hd-180-1 

也期待在examples with IndexOfexamples with substring

0

或许你也可以使用string.split:

List<string> list = yourString.Split("."); 
List<string> keeping = list.Where(s => !s.Contains("hd") && !s.Contains("hr")) 
return String.Join(".", keeping); 
+0

它有时可能是第三项,它是随机的,你会看到。 – x06265616e

+0

你可以拆分,然后匹配每个条目保留或删除,如果这使事情更容易。 –

+0

@ x06265616e,我编辑了答案以反映随机位置。 –

0

你可以使用正则表达式

string data = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64"; 

//Match things that are preceded by a dot (.) (or the beginning of input) 
// that begin with 'h' followed by a single letter, then dash, three digits, 
// a dash, at least one digit, followed by a period (or the end of input) 
var rx = new Regex(@"(?<=(^|\.))h\w-\d{3}-\d+(\.|$)"); 

//Get the matching strings found 
var matches = rx.Matches(data); 

//Print out the matches, trimming off the dot at the end 
foreach (Match match in matches) 
{ 
    Console.WriteLine(match.Value.TrimEnd('.')); 
} 

//Get a new copy of the string with the matched sections removed 
var result = rx.Replace(data, "").TrimEnd('.'); 
0

我发现了一个功能在线的作品......

  public static string RemoveBetween(string s, string begin, string end) 
      { 
       Regex regex = new Regex(string.Format("{0}{1}", begin, end)); 
       return regex.Replace(s, string.Empty); 
      } 
+2

你传递给那个函数的是什么'begin'和'end'? – I4V