0

I have a input which can be the following (Either one of these three):

  • 1-8…in other words 1, 2,3,4,5,6,7,8
  • A-Z….in other words, A, B, C, D etc
  • 01-98…in other words, 01,02,03,04 etc

I came up with this regex but it's not working not sure why:

@"[A-Z0-9][1-8]-

I am thinking to check for corner cases like just 0 and just 9 after regex check because regex check isn't validating this

1
  • So it can be only one of those? Commented Jan 21, 2014 at 9:39

5 Answers 5

3

Not sure I understand, but how about:

^(?:[A-Z]|[1-8]|0[1-9]|[1-8][0-9]|9[0-8])$

Explanation:

(?:...) is a group without capture.
| introduces an alternative
[A-Z] means one letter
[1-8] one digit between 1 and 8
0[1-9] a 0 followed by a digit between 1 and 9
[1-8][0-9] a digit between 1 and 8 followed by a digit between 1 and 9
9[0-8] 9 followed by a digit between 0 and 8

May be it is, depending on your real needs:

^(?:[A-Z]|[0-9]?[1-8])$
Sign up to request clarification or add additional context in comments.

6 Comments

@M42, ^(?:[A-Z]|[1-8]|0[1-9]|[1-8][0-9]|9[0-8])$ seems to work. Is it possible for you to explain a bit how is it working?
I would personally use your first regex with a slight modification: ^(?:[A-Z]|0[1-9]|[1-8][0-9]?|9[0-8])$ That should cover everything the second one fails to.
@Jerry: You're right for the first one. For the second regex, I supposed OP wanted only numbers that end with digit between 1 and 8 as it's not really clear in the question.
@M42, Thanks m42. Just 1 question, what does "is a group without capture mean?"
Yes, that wasn't entirely clear indeed. Only @Charu can confirm this.
|
1

I think you may use this pattern

@"^([1-8A-Z]|0[1-9]|[1-9]{2})$"

Comments

0

What about ^([1-8]|([0-9][0-9])|[A-Z])$ ?

That will give a match for

A 8 (but not 9) 09

Comments

0
[1-8]{0,1}[A-Z]{0,1}\d{1,2}

matches all of the following

8A8 8B9 9 0 00 

Comments

0

You can use following pattern:

^[1-8][A-Z](?:0[1-9]|[1-8][0-9]|9[0-8])$
  • ^[1-8] - input should start with number 1-8
  • [A-Z] - then should be single letter A-Z
  • (0[1-9]|[1-8][0-9]|9[0-8])$ and it should end with two numbers which are 01-19 or 10-89 or 90-98

Test:

string pattern = @"^[1-8][A-Z](0[1-9]|[1-8][0-9]|9[0-8])$";
Regex regex = new Regex(pattern);
string[] valid = { "1A01", "8Z98" };
bool allMatch = valid.All(regex.IsMatch);
string[] invalid = { "0A01", "11A01", "1A1", "1A99", "1A00", "101", "1AA01" };
bool allNotMatch = !invalid.Any(regex.IsMatch);

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.