如何删除字符串的已定义部分?

我有这个字符串:“NT-DOM-NV \ MTA”如何删除第一部分:“NT-DOM-NV \”结果如下:“MTA”

RegEx怎么可能?

您可以使用

str = str.SubString (10); // to remove the first 10 characters. str = str.Remove (0, 10); // to remove the first 10 characters str = str.Replace ("NT-DOM-NV\\", ""); // to replace the specific text with blank // to delete anything before \ int i = str.IndexOf('\\'); if (i >= 0) str = str.SubString(i+1); 

鉴于“\”始终出现在字符串中

 var s = @"NT-DOM-NV\MTA"; var r = s.Substring(s.IndexOf(@"\") + 1); // r now contains "MTA" 
 string.TrimStart(what_to_cut); // Will remove the what_to_cut from the string as long as the string starts with it. 

"asdasdfghj".TrimStart("asd" ); 将导致"fghj"
"qwertyuiop".TrimStart("qwerty"); 将导致"uiop"


 public static System.String CutStart(this System.String s, System.String what) { if (s.StartsWith(what)) return s.Substring(what.Length); else return s; } 

"asdasdfghj".CutStart("asd" ); 现在将导致"asdfghj"
"qwertyuiop".CutStart("qwerty"); 仍将导致"uiop"

如果始终只有一个反斜杠,请使用:

 string result = yourString.Split('\\').Skip(1).FirstOrDefault(); 

如果有多个而你只想拥有最后一部分,请使用:

 string result = yourString.SubString(yourString.LastIndexOf('\\') + 1); 

尝试

 string string1 = @"NT-DOM-NV\MTA"; string string2 = @"NT-DOM-NV\"; string result = string1.Replace( string2, "" ); 
  string s = @"NT-DOM-NV\MTA"; s = s.Substring(10,3); 

您可以使用此扩展方法:

 public static String RemoveStart(this string s, string text) { return s.Substring(s.IndexOf(s) + text.Length, s.Length - text.Length); } 

在您的情况下,您可以按如下方式使用它:

 string source = "NT-DOM-NV\MTA"; string result = source.RemoveStart("NT-DOM-NV\"); // result = "MTA" 

注意:不要使用TrimStart方法,因为它可能会进一步修剪一个或多个字符( 请参阅此处 )。

 Regex.Replace(@"NT-DOM-NV\MTA", @"(?:[^\\]+\\)?([^\\]+)", "$1") 

试试吧。