Sudhanva
Sudhanva

Reputation: 21

Prevent leading and trailing spaces with RegExp

We are looking for a RegExp which satisfies the following conditions:

  1. The first 3 characters should be alphanumeric without spaces.
  2. Next characters can be alphanumeric including spaces.
  3. The pattern should not end with a space.
  4. The length should be 3 to 20 characters.

We have something like this currently :

^[A-Za-z0-9]{3}[\\sA-Za-z0-9]{0,16}[A-Za-z0-9]$

But the above Reg Exp accepts a minimum length of 4 characters and not 3. I am mainly facing problem in limiting the length from 3 to 20 along with the requirement that first 3 characters must be alphanumeric.

Upvotes: 0

Views: 2339

Answers (4)

sunbabaphu
sunbabaphu

Reputation: 1493

^[A-Za-z0-9]{3}[\sA-za-z0-9]{0,17}(?<!\s)$

(?<!\s)$: negative lookbehind - so that the $ character is not preceded by a \s, i.e. there's no space at the end (allows multiple spaces in between characters)

--> DEMO

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You could use the below regex,

^(?=.{3,20}$)(?:[A-Za-z0-9]){3}(?:(?:[A-Za-z0-9 ]+)?[A-Za-z0-9]+)*

DEMO

Upvotes: 0

sharcashmo
sharcashmo

Reputation: 815

What about?

^[A-Za-z0-9]{3}([\\sA-Za-z0-9]{0,16}[A-Za-z0-9])?$

Just making everything beyond the 3 leading characters optional should work.

Upvotes: 1

zx81
zx81

Reputation: 41838

You can use this:

(?i)^[a-z0-9]{3}(?:[a-z0-9 ]{0,16}[a-z0-9])?$

You can test it out in this demo.

  • The (?i) makes it case-insensitive
  • The ^ anchor asserts that we are at the beginning of the string
  • [a-z0-9]{3} matches the first three chars
  • Optionally (thanks to the ?), we match...
  • [a-z0-9 ]{0,16} 0 to 16 alphanums or spaces, then an alphanum [a-z0-9]
  • The $ anchor asserts that we are at the end of the string

Upvotes: 1

Related Questions