Sasha Shpota
Sasha Shpota

Reputation: 10310

RegEx: fixed length letters followed by numbers

I need a regex that allows to enter lets say 5 symbols - letters or digits but letters should be always followed by digits?

It needs to be something like [0-5 letters][0-5 digits] but the total length of the string should be 5 symbols.

The problem is that I can't manage to limit the length of the string after applying first two expressions.

I've tried something like

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

but it is not what I want - it doesn't restrict length.

Examples:

Examples that shouldn't match:

Upvotes: 0

Views: 1205

Answers (1)

akuiper
akuiper

Reputation: 215117

You can use a look ahead assertion (?=.{5}$) at the beginning of regex to assert the string is always length of five:

var samples = ['AAAAA',         // match
               'AA777',         // match
               '77777',         // match
               'AAA7A',         // doesn't match pattern
               '77AAA',         // doesn't match pattern
               'AAA777'         // match the pattern but doesn't match the length
              ]

console.log(
  samples.map(s => /^(?=.{5}$)[a-zA-Z]*[0-9]*$/.test(s))
)

Upvotes: 2

Related Questions