假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
假设我有一个字符串:
"34234234d124"
我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。
是否有可能在c#的一个表达式中得到这个结果?
当前回答
这对于任何长度的字符串都不会失败。
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
对于当前的任务来说,这可能有些多余,但如果需要进行额外的验证,则可以将其添加到正则表达式中。
编辑:我认为这个正则表达式会更有效:
@".{4}\Z"
其他回答
建议使用TakeLast方法,例如:new String(text.TakeLast(4).ToArray())
对我来说,使用范围操作符是最简单的方法。不需要太多代码。
在你的情况下,你可以得到你想要的:
// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?
如果你确定字符串的长度至少是4,那么它甚至更短:
mystring.Substring(mystring.Length - 4);
string x = "34234234d124";
string y = x.Substring(x.Length - 4);
mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;