Tonyukuk
Tonyukuk

Reputation: 6195

Regex for a letter as first char and four digits after

I want to have a regex to validate a string starting with a letter and then digits, but the string length should be limited to 5 chars.

Regex Expression I am using:

Validators.pattern('(.*?)[0-9]{4}')

Unfortunately, it does not give me validation message (error message) when the digit is more than 5. Could you please check my regex expression and tell me where I am doing wrong ?

Upvotes: 0

Views: 4411

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

A .*? pattern matches any 0+ characters (by a character, I mean all possible symbols, letters, digits), as few as possible, up to the first occurrence of the subsequent subpatterns.

What you need is to match a single ASCII letter at the start of the string, and then assure there are just 4 digits after it. Since Validators.pattern() patterns are anchored by default, you just need to use

Validators.pattern('[A-Za-z][0-9]{4}')

The pattern will get translated to /^[A-Za-z][0-9]{4}$/.

See the regex demo.

NOTE: if you ever need to match this pattern inside a longer string to extract the pattern occurrences, use word boundaries instead of anchors, \b[A-Za-z][0-9]{4}\b.

Upvotes: 2

Related Questions