Extract only right most n letters from a string

2019-01-13 14:13发布

How can I extract a substring which is composed of the rightmost six letters from another string?

Ex: my string is "PER 343573". Now I want to extract only "343573".

How can I do this?

21条回答
Ridiculous、
2楼-- · 2019-01-13 14:45
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
查看更多
唯我独甜
3楼-- · 2019-01-13 14:46

MSDN

String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);

EDIT: too slow...

查看更多
狗以群分
4楼-- · 2019-01-13 14:46

Null Safe Methods :

Strings shorter than the max length returning the original string

String Right Extension Method

public static string Right(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());

String Left Extension Method

public static string Left(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Take(count));
查看更多
看我几分像从前
5楼-- · 2019-01-13 14:47

Just a thought:

public static string Right(this string @this, int length) {
    return @this.Substring(Math.Max(@this.Length - length, 0));
}
查看更多
爷的心禁止访问
6楼-- · 2019-01-13 14:49

Guessing at your requirements but the following regular expression will yield only on 6 alphanumerics before the end of the string and no match otherwise.

string result = Regex.Match("PER 343573", @"[a-zA-Z\d]{6}$").Value;
查看更多
\"骚年 ilove
7楼-- · 2019-01-13 14:53

Probably nicer to use an extension method:

public static class StringExtensions
{
    public static string Right(this string str, int length)
    {
        return str.Substring(str.Length - length, length);
    }
}

Usage

string myStr = "ABCDEPER 343573";
string subStr = myStr.Right(6);
查看更多
登录 后发表回答