c# - Check if string ends with 4 numbers

Regex.Match can be used to test a string against a regular expression. It returns a Match-object where the Success property shows if a match was made.

Regex.Match(yourString, @"\d{4}$").Success

Use this in your test to see if yourString ends in four digits.

Regards


Try this:

\d{4}$

\d matches a digit, the {4} quantifier states that there must be 4 of the previous token (4 digits) and $ defines the string end.

An example of using $:

# RegEx foo
foo       # Match
barfoo    # Match
foobar    # Match

# RegEx foo$
foo       # Match
barfoo    # Match
foobar    # No Match

Live Demo on Regex101

Demo


Here is one way to do it:

string str = "MVI_2546";

bool match =
    str.Length >= 4 && //Make sure that the string has at least 4 characters
    str.Substring(str.Length - 4) //Check that the last 4 characters
        .All(char.IsDigit); //are all digits.

Tags:

C#

Regex

Numbers