0

So I want to check that a string has all these attributes:

  • Five characters long, and
  • The first character is one of:
    • O, or
    • S, or
    • J, or
    • C, and
  • The last four characters are digits.

This is my code:

Console.Write("IDnumber : ");
IDnumber= Console.ReadLine();
IDnumberLength = IDnumber.Length;
if (MemberNumber.Length == 5  && 
    char.IsLetter(IDnumber[0]) &&  <-- I know how to validate any letter but not certain letter
    char.IsDigit(IDnumber[1]) && 
    char.IsDigit(IDnumber[2]) &&
    char.IsDigit(IDnumber[3]) &&
    char.IsDigit(IDnumber[4]))
2
  • 3
    Sounds like the regular expression [OSJC][0-9]{4} would fit. Alternatively, your code plus new char[] { 'O', 'S', 'J', 'C' }.Contains(IDnumber[0]). Commented Nov 27, 2016 at 0:33
  • 1
    just keep in mind that the char.Is methods also check for Unicode characters fileformat.info/info/unicode/category/Nd/list.htm, so IDnumber[1] >= '0' && IDnumber[1] <= '9' might be preferred Commented Nov 27, 2016 at 0:53

2 Answers 2

4

You could use Regex like this:

var regex = new Regex("^[OSJC][0-9]{4}$");

Console.WriteLine(regex.IsMatch("J1234"));
Console.WriteLine(regex.IsMatch("J124"));
Console.WriteLine(regex.IsMatch("X1234"));

That would give you:

True
False
False

In your code you could use it like this:

Console.Write("IDnumber : ");
IDnumber = Console.ReadLine();
if (Regex.IsMatch(IDnumber, "^[OSJC][0-9]{4}$"))
{
    // Success
}
else
{
    // Failed
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd add anchors for the front and back. This regex also matches 1O1234x.
0

Without using a regular-expressions:

Boolean isValid =
    value.Length == 5 &&
    ( value[0] == 'O' || value[0] == 'S' || value[0] == 'J' || value[0] == 'C' ) &&
    Char.IsDigit( value[1] ) &&
    Char.IsDigit( value[2] ) &&
    Char.IsDigit( value[3] ) &&
    Char.IsDigit( value[4] );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.