我如何在c#中获取字符串的最后3位数字

问题描述 投票:1回答:3

如何获得此string后三位数字

var myString = "77441-Megrhfj654JHK";
c#
3个回答
3
投票

您可以尝试正则表达式

  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

0
投票

非常简单的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上的工作示例


0
投票

在C#8中,您可以使用rangestring[^3..];

仅对于数字,类似:new string(strin.Where(char.IsDigit).ToArray())[^3..];

© www.soinside.com 2019 - 2024. All rights reserved.