oayardimovic
oayardimovic

Reputation: 11

C# .Net RegEx: first 3 char must be a number between 1-100 and second 3 char can be any char

I'm trying to set RegEx for a console application. And my problem is to define RegEx expression.

I tried;

^([1-9][0-9]?|^100){3}[a-zA-Z]{3}$

and

^[0-9]{3}[a-zA-Z]{3}$

but I couln't solve it.

Regex r = new Regex(@"^([1-9][0-9]?|^100){3}[a-zA-Z]{3}$");

if (r.IsMatch(textBox1.Text)) { MessageBox.Show("OK"); } else { MessageBox.Show("NO"); }

First 3 must be a number between 1-100 and second 3 must be any three chars like "123ABC" or "405006ghd" or "7093zyx".

Upvotes: 1

Views: 210

Answers (2)

Konrad Neitzel
Konrad Neitzel

Reputation: 760

Your description is not 100% clear.

Your description verbally is: 3 characters that form a number between 1 and 100 and then 3 characters that can be any character.

So the first block would mean 001 to 100 and the second block is any character so it could be "aaa" but also "123" or "..."

In your regular expressions, you used the begin and end of the string (^ and $) so the match must be exact. But then your examples are wrong, because you gave examples with more than 6 characters ...

But let us start some building of regular expressions: We know, that the first character is either a 0 or a 1 and the following are a character of the range 0-9. So we could start with [01][0-9][0-9]. But that will also include the 000 but we wanted to start with 001.

So we exclude the 000: (?!000)[01][0-9][0-9]

Edit: I missed the upper limit of 100 here. So I would recommend something like 100|0[1-9][0-9]|00[1-9] which does not need any exclude and is easier to read.

The last 3 characters is now easy: .{3} matches any 3 characters.

So we get at the end: (?:100|0[1-9][0-9]|00[1-9]).{3}

And you can test the regular expression at https://regex101.com/

Of course: If you want complete matches, then you have to add the ^ and $ again. If you do not want any character, then replace the . with the characters you want to allow there.

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163467

In your pattern you can remove the ^ from ^100 because that is already specified at the start of the pattern.

In your example data 405006ghd does not match because [1-9][0-9]? will not allow a leading zero so it can not match the 06

You could match either 100, or a number 1 - 99 or a number 0-9 with an optional leading zero:

^(?:100|[1-9][0-9]|0?[1-9]){3}[a-zA-Z]{3}$

In detail

  • ^ Start of the string
  • (?: Non capturing group
    • 100 Match literally
    • | Or
    • [1-9][0-9] Match 10 - 99
    • | Or
    • 0?[1-9] Match 1-9 with optional leading 0
  • ){3} Close non capturing group and repeat 3 times
  • [a-zA-Z]{3} Match a-z A-Z 3 times
  • $ End of string

Regex demo

Upvotes: 1

Related Questions