2

I have the following regex pattern:

"[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}"

and I want to validate a string with the following conditions

  • allow only alphanumeric characters
  • has length of only 8 or 11
  • first 6 characters must all be uppercase letters

However, the above pattern is not working. What needs to be changed?

3
  • Try Regexhero.net its good tool for testing your expressions. Commented Mar 7, 2014 at 9:06
  • Try this one : (?:[a-zA-Z]{8,11}\d+) Commented Mar 7, 2014 at 9:10
  • If you want more accurate answer. you should paste some examples. Commented Mar 7, 2014 at 9:11

2 Answers 2

7

Use following regular expression:

^[A-Z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$

First 6 characters must all be uppercase letters (^ means that following pattern should match at the start of the string):

^[A-Z]{6}

Now there should be 2 or 5 more alphanumeric characters; 2 alphanumeric chracters should come anyway:

[A-Za-z0-9]{2}

and 3 after that is optional (?: 0 or 1 match of the preceding pattern, $ means that preceding pattern should match at the end of the string):

([A-Za-z0-9]{3})?$

Using ^ and $ together (^PATTERN$), the pattern should match the whole string instead of the substring.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice detailed explanation. Very pedagogical! :) For completeness, you might add that ^ means that that part of the patterns must be at the start of the target string (anchored to it's start), and that $ anchors the other end to the end of the string in the same way, so that this pattern must represent the whole target string.
@Kjartan, Thank you for the advice. I added an explanation about ^, $.
1

The expression should be:

^[A-Z]{6}([A-Za-z0-9]{2}|[A-Za-z0-9]{5})$

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.