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

Tas*_*sto 16 c# regex asp.net string

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

RegEx怎么可能?

Fun*_*eng 43

您可以使用

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);
Run Code Online (Sandbox Code Playgroud)


Mik*_*erg 10

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

var s = @"NT-DOM-NV\MTA";
var r = s.Substring(s.IndexOf(@"\") + 1);
// r now contains "MTA"
Run Code Online (Sandbox Code Playgroud)


Ver*_*cas 8

string.TrimStart(what_to_cut); // Will remove the what_to_cut from the string as long as the string starts with it.  
Run Code Online (Sandbox Code Playgroud)

"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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 有线问题。我想很多开发者都不知道这一点。无论如何,这是一个非常好的和清晰的解决方案,我将我们应用程序中的 ALL TrimStart 替换为您的 CutStart 方法。谢谢你。 (3认同)