Smegal
Smegal

Reputation: 35

Validate a string of certain characters and numeric of exact length using Regex

Objective:match exact 10 of mixed uppercase characters (except I,O, and space) and numeric from 2 to 9:

To be exact, here is the valid set the value must be coming from:

{'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K','L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}

I have tried this:

^[A-Z2-9][^IO01a-z ]{10}$

But this 11 length would pass: 9PAUUH98TYE while 10 of them wouldn't pass 9PAUUH98TY

I also tried:

\b[A-Z2-9][^IO01a-z ]{10}\b

Upvotes: 1

Views: 134

Answers (3)

gunr2171
gunr2171

Reputation: 17579

So you could do some fancy negative lookaround magic, but really, just listing out the letters you expect is fine.

^[ABCDEFGHJKLMNPQRSTUVWXYZ2-9]{10}$

Using spanning, it can be shortened to

^[A-HJ-NP-Z2-9]{10}$

This is the """lazy""" method, but it will work consistently the same across all regex flavors. Negative lookbehinds sometimes might behave differently in .Net vs JavaScript vs others, for example.

Also, it's SUPER important to use ^ and $ in your pattern. They will help to ensure that the whole input string is the correct number of characters.

Upvotes: 3

vedda
vedda

Reputation: 46

Would this work?

\b[A-HJ-NP-Z2-9]{10}\b

Demo

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20953

You can use negative lookahead/lookbehind to exclude the set you don't want:

\b([A-Z2-9](?<![IO])){10}\b

Check here to see the test cases

Upvotes: 1

Related Questions