如何获得此string
的后三位数字?
var myString = "77441-Megrhfj654JHK";
您可以尝试正则表达式:
using System.Text.RegularExpressions;
...
var myString = "77441-Megrhfj654JHK";
// Exactly 3 digits while start matching from the right
string digits = Regex.Match(myString, "[0-9]{3}", RegexOptions.RightToLeft).Value;
Console.WriteLine(digits);
结果:
654
非常简单的LINQ示例
public static class StringExtensions
{
public static string GetLastDigits( this string source, int count )
{
return new string( source
.Where(ch => Char.IsDigit(ch))
.Reverse()
.Take(3)
.Reverse()
.ToArray());
}
}
请参见.net fiddle上的工作示例
在C#8中,您可以使用range:string[^3..];
仅对于数字,类似:new string(strin.Where(char.IsDigit).ToArray())[^3..];
。