ABHIJIT
ABHIJIT

Reputation: 689

regex few blocks exact length

I want to match 5 to 20 character with regex. I try to use below regular expression for my checking.

/^[a-zA-Z][\w]{5,20}$/

It's work, but the problem of length it match 6 to 21 character.

(^[a-zA-Z][\w]){4,20}$

I also try this but it don't work.

Please anyone help me to match exact length of regex.

Upvotes: 1

Views: 399

Answers (3)

NineBerry
NineBerry

Reputation: 28509

The Quantifier is only applied to the [\w]. So this expects exactly one letter character and then 5-20 whitespace characters.

I assume you want 5-20 characters that can be either a letter a-z or a whitespace. You need to group these together in square brackets and then apply the quantifier:

^[a-zA-Z\W]{5,20}$

So, I understand, you want a string that has 5-20 characters, starts with a letter and then only has letters and digits. You would write it like that:

^[a-zA-Z][a-zA-Z0-9]{4,19}$

This expects first a letter and then 4-19 letters or digits.

BTW: https://regex101.com/ is a great site to test regular expressions and get an explanation what they are doing.

Upvotes: 2

slartidan
slartidan

Reputation: 21618

/^[a-zA-Z][\w]{5,20}$/ means:

  • a character from a to z in lower or upper case
  • 5 to 20 word characters

That sums up to 6 to 21 characters in total.


I suppose you want /^[a-zA-Z][\w]{4,19}$/:

  • a character from a to z in lower or upper case
  • 4 to 19 word characters

That sums up to 5 to 20 characters in total.

Upvotes: 2

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

It's because your capturing group is expecting TWO characters: [a-zA-Z] and [\w], that's two letters.

So your first attempt actually did this:

  • match [a-zA-Z] once
  • match [\w] once
  • match the previous matches 5 - 20 times
  • Inevitably, you always had 1 more match than expected

Capture only one character, and iterate it 5-20 times. Have you tried: ^([a-zA-Z]{5,20})$ ? OR ^(\w{5,20})$ ?

You're almost there, you just need to make a single range of characters (in square brackets) not two.

Upvotes: 2

Related Questions