1
pattern="^[01|02|03|07|08]{1}[0-9]{8-10}$"

I need 9-12 characters starting with 01, 02, 03, 07 or 08. Why is my pattern not working?

1
  • 1
    Test it in REGEX generator. There are lots out there. Commented Aug 16, 2018 at 14:20

3 Answers 3

2

You don't need ^ and $. I tried to simplify your pattern:

  • Changed [01|02…08] to 0(1|2…8) because you need to use parenthesis as chevybow explained,
  • Changed {8-10} to {7,10} because you said you “need 9-12 characters”, and - doesn't work in the {}.

This snippet works for me:

<form>
  <input pattern="0(1|2|3|7|8)[0-9]{7,10}" />
  <input type="submit" />
</form>

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

2 Comments

0|12345678 submits for your snippet
@chevybow True, need parenthesis.
1

This should work for you

^(01|02|03|07|08){1}[0-9]{8,10}$

Your issue was using [] instead of () checking for the first numbers. You need parenthesis with the logical ors. The way you had it you were matching literally against just one character of either any number or |.

For example:

012345678 would have matched, as would have |12345678 with the pattern you were using

Comments

1

I think you tried to use an alternation (01|02|03|07|08) instead of using the digits in a character class [01|02|03|07|08]

But even when you use the version with the alternation, that would match 2 digits and would in your regex be followed by [0-9]{8-10} which will be a total of matching 10 - 12 digits instead of the 9 - 12

You could put the prepending zero before the charcter class and leave 12378 inside the character class. That would be 2 characters, leaving matching 7 -10 following digits.

You don't need the ^ and $ because the regex is already anchored.

0[12378][0-9]{7,10}

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.