Share via

Simple expression

Ian Brooke 1 Reputation point
2021-07-24T17:31:00.74+00:00

I am convinced that this requirement is so simple it's embarrassing to ask but for some reason it is escaping me, perhaps I don't know enough about Regular Expressions. :)
All I need to do is validate a string which needs to match 1-4 numbers followed optionally by a single letter (upper or lower case a-z). so 9, 8a, 225z are all valid but, a, 2ab, 12345a, are invalid.
All help very welcome!

ps I have no idea what I'm wanted to enter under "Tags" so I just picked one at random!

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

2 answers

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2021-07-26T08:55:49.983+00:00

    Try this simple expression too:

    ^[0-9]{1,4}[a-zA-Z]?$

    Was this answer helpful?

    0 comments No comments

  2. Timon Yang-MSFT 9,611 Reputation points
    2021-07-26T06:05:21.96+00:00

    Please try if this can meet your needs:

                Regex regex = new Regex(@"(?<=^[0-9]{1,3}(?:a|A|z|Z|$)\b)");  
                string test = "123a";  
                bool re = regex.IsMatch(test);  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.