2012-08-06 278 views
1

我有一些字符串,就像FFS\D46_24\43_2我想返回第一個反斜槓和最後一個下劃線之間的文本。在上面的例子中的情況下,我想D46_24\43刪除字符串的特定部分

我嘗試下面的代碼,但它拋出參數超出範圍exepction的:

public string GetTestName(string text) 
    { 
     return text.Remove(
      text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase) 
      , 
      text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase) 
      ); 
    } 

回答

8

第二個參數是一個數,而不是一個結束索引。此外,隔離部分字符串的正確方法是Substring而不是Remove。所以你必須寫它作爲

var start = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase); 
var end = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase); 

// no error checking: assumes both indexes are positive 
return text.Substring(start + 1, end - start - 1); 
3

第二個參數不是結束索引 - 它應該是要刪除的字符數。

請參閱the documentation這個過載。

int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase); 
int endIndex = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase) 

return text.Remove(startIndex, endIndex - startIndex); 
1

這是正則表達式的工作。

var regex = new Regex(@"\\(.+)_"); 
var match = regex.Match(@"FFS\D46_24\43_2"); 

if(match.Success) 
{ 
    // you can loop through the captured groups to see what you've captured 
    foreach(Group group in match.Groups) 
    { 
     Console.WriteLine(group.Value); 
    } 
} 
+0

...現在你有兩個問題。 ;-)你正在使用'Groups [1]' - 如果輸入字符串是「@」FFS \ D46-24 \ 43_2「'? – 2012-08-06 12:20:25

+0

@DanPuzey真實而好的一點 - 只是在這種情況下提供一個例子。我會重新寫它更安全。 – 2012-08-06 12:22:27

1

使用正則表達式:

Match re = Regex.Match("FFS\D46_24\43_2", @"(?<=\\)(.+)(?=_)"); 
if (re.Success) 
{ 
    //todo 
} 
0

您應該使用,而不是刪除子串。 試試這個:

public static string GetTestName(string text) 
    { 
     int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase); 
     int endIndex = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase); 

     if (startIndex < 0 || endIndex < 0) 
      throw new ArgumentException("Invalid string: no \\ or _ found in it."); 

     if (startIndex == text.Length - 1) 
      throw new ArgumentException("Invalid string: the first \\ is at the end of it."); 

     return text.Substring(startIndex + 1, 
           endIndex - startIndex - 1); 
    } 
0
string text = @"FFS\D46_24\43_2"; 
int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase), 
    lastIndex = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase); 

return text.Substring(startIndex + 1, lastIndex-startIndex-1);