3

I'm new to regex syntax and am looking for a way to match the following criteria:

  1. String has 1 alpha character and the rest are digits
  2. String starts with at least 1 digit but no more than 3
  3. Following character is a single alpha character (upper or lower case a-Z)
  4. Followed by 4 to 6 digits

Example valid data:

1A1111
1A11111
1A111111
11A1111
11A11111
11A111111
111A1111
111A11111
111A111111

Most examples I'm finding are matching 1 or more of a value so I'm struggling with how to match specific number of characters and what place they can be found in.

For example:

Matching 1 or more digits at the start of the string: @"^\d"

or Making sure the string has at least one Alpha character:

bool match = Regex.IsMatch(tokenString, @"(?=.*[^a-zA-Z])", RegexOptions.IgnoreCase);

But this doesn't tell it that there can be only 1 alpha character.

1
  • 1 or more digits at the start of the string. Use the OR (ie. | ) modifier in your Regex. I think that's what you are missing, if not let me link Commented Dec 20, 2013 at 17:26

3 Answers 3

6

This will work

^\d{1,3}[a-zA-Z]\d{4,6}$

breakdown:

^        - match at beginning
\d{1,3}  - one to three digits
[a-zA-Z] - one letter a-z or A-Z
\d{4,6}  - followed by between 4 and 6 digits
$        - and that's end of the string...  
Sign up to request clarification or add additional context in comments.

1 Comment

You guys make it look so easy :-) Thanks for the break down explanation.
3

Try using this one.

^\d{1,3}[a-zA-Z]\d{4,6}$

Comments

3

The following pattern should do what you are asking for:

^\d{1,3}[a-zA-Z]\d{4,6}$

Well, since you are using RegexOptions.IgnoreCase, you can get away with just:

^\d{1,3}[a-z]\d{4,6}$

For more info on what you can do with Regular Expressions, go here:

http://www.regular-expressions.info/reference.html

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.