1

I am trying to make a JavaScript Regex which satisfies the following conditions

  1. a-z are possible
  2. 0-9 are possible
  3. dash, underscore, apostrophe, period are possible
  4. ampersand, bracket, comma, plus are not possible
  5. consecutive periods are not possible
  6. period cannot be located in the start and the end
  7. max 64 characters

Till now, I have come to following regex

^[^.][a-zA-Z0-9-_\.']+[^.]$

However, this allows consecutive dot characters in the middle and does not check for length. Could anyone guide me how to add these 2 conditions?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Waqar Ahmad
  • 3,716
  • 1
  • 16
  • 27
  • 1
    I would expect for the length check to use the `.length` property to be much faster than some Regex construct. – Uwe Keim May 27 '19 at 05:23

3 Answers3

2

Here is a pattern which seems to work:

^(?!.*\.\.)[a-zA-Z0-9_'-](?:[a-zA-Z0-9_'.-]{0,62}[a-zA-Z0-9_'-])?$

Demo

Here is an explanation of the regex pattern:

^                          from the start of the string
    (?!.*\.\.)             assert that two consecutive dots do not appear anywhere
    [a-zA-Z0-9_'-]         match an initial character (not dot)
    (?:                    do not capture
    [a-zA-Z0-9_'.-]{0,62}  match to 62 characters, including dot
    [a-zA-Z0-9_'-]         ending with a character, excluding dot
     )?                    zero or one time
$                          end of the string
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

You can use this regex

^(?!^[.])(?!.*[.]$)(?!.*[.]{2})[\w.'-]{1,64}$

Regex Breakdown

^ #Start of string
(?!^[.]) #Dot should not be in start
(?!.*[.]$) #Dot should not be in start
(?!.*[.]{2}) #No consecutive two dots
[\w.'-]{1,64} #Match with the character set at least one times and at most 64 times.
$ #End of string

Correction in your regex

  • - shouldn't be in between of character class. It denotes range. Avoid using it in between
  • [a-zA-Z0-9_] is equivalent to \w
rock321987
  • 10,942
  • 1
  • 30
  • 43
1

Here comes my idea. Used \w (short for word character).

^(?!.{65})[\w'-]+(?:\.[\w'-]+)*$
  • ^ at start (?!.{65}) look ahead for not more than 64 characters
  • followed by [\w'-]+ one or more of [a-zA-Z0-9_'-]
  • followed by (?:\.?[\w'-]+)* any amount of non capturing group containing a period . followed by one or more [a-zA-Z0-9_'-] until $ end

And the demo at regex101 for trying

bobble bubble
  • 16,888
  • 3
  • 27
  • 46