-1

I am poor with Regular expressions, following is the requirement. I will be using this with Joi validators.

ID :

  • Should be alphanumeric
  • Cannot have any special characters except dash and underscore (- and _)
  • Cannot have - or _ consecutively (Example: this-id is ok but this--id is not.

Name:

  • Should be alphanumeric
  • Cannot have any special characters except dash and underscore (- and _), but space is allowed.
  • Cannot have - or _ consecutively (Example: this-id is ok but this--id is not.
Aman
  • 623
  • 1
  • 11
  • 23

3 Answers3

3

Regex for ID:

^[-_]?(?:[A-Za-z0-9]+[-_]?)+$
  • [-_]? allows underscore or hyphen to appear at the start too
  • [A-Za-z0-9]+ matches one or more alphanumeric characters
  • [-_]? allows zero or one hyphen or underscore
  • Whole pattern is surrounded within a non capturing group and a + to indicate that it may repeat one or more times

Thus is ensures that no 2 hyphens or underscores appear in succession

Regex101 Demo

Regex for Name:

^[-_]?(?:[A-Za-z0-9 ]+[-_]?)+$

EDIT: Improvement to fix underscore or hyphen appearing at the start too. Thanks to @ErikBrodyDreyer for the catch! :)

degant
  • 4,861
  • 1
  • 17
  • 29
  • That won't match the case where the ID begins with a hyphen or underscore, if that case needs to be accepted too. – E.D. May 31 '17 at 19:17
  • 2
    @ErikBrodyDreyer good point, missed that. Can be fixed by adding `[-_]?` at the start, outside the non-capturing group – degant May 31 '17 at 19:22
0

([a-zA-Z0-9]*(_)?(?!\2)(\-)?(?!\3))+

this will do the work it will match also -_ prefix

Or Davidi
  • 99
  • 7
0

ID : ^(?!.*([_-])\1)[\w-]+$

Name : ^(?!.*([_-])\1)[\w -]+$

A \w is the same as [A-Za-z0-9_], so the underscore is included.

The (?!.*([_-])\1) is a negative lookahead that won't allow a double dash or double underscore after the start of the string ^.

LukStorms
  • 28,916
  • 5
  • 31
  • 45