Home > OS >  Regex to allow special only between alpha numeric
Regex to allow special only between alpha numeric

Time:08-18

I need a REGEX which should validate only if a string starts and ends with Alphabets or numbers and should allow below special characters in between them as below:

/*
hello  -> pass
what -> pass
how @@are you -> pass
how are you? -> pass
hi5kjjv  -> pass
8ask -> pass
yyyy. -> fail
! dff -> fail
NoSpeci@@@alcharacters -> pass
Q54445566.00 -> pass
q!Q1 -> pass
!Q1 -> fail
q!! -> fail
#NO -> fail
0.2Version -> pass
-0.2Version -> fail
*/

the rex works fine for above query but the issue is it expects at least two valid characters:

^[A-Za-z0-9] [ A-Za-z0-9_@./#& $%_=;?\'\,\!-]*[A-Za-z0-9]  

failing in case if we pass:

a -> failed but valid
1 -> failed but valid

I tried replacing with * but this was accepting special characters from the start (@john) which is wrong.

[A-Za-z0-9]   with [A-Za-z0-9]* 

CodePudding user response:

You may use this regex:

^[A-Za-z0-9](?:[! #$%;&' ,./=?@\w-]*[A-Za-z0-9?])?$

Or if your regex flavor supports atomic groups then use a bit more efficient:

^[A-Za-z0-9](?>[! #$%;&' ,./=?@\w-]*[A-Za-z0-9?])?$

RegEx Demo

RegEx Details:

  • ^: Start
  • [A-Za-z0-9]: Match an alphanumeric character
  • (?>[! #$%;&' ,./=?@\w-]*[A-Za-z0-9?])?: Optional atomic group to match 0 or more of a specified char in [...] followed by an alphanumeric or ? characters
  • $: End
  • Related