Muthamizhchelvan. V
Muthamizhchelvan. V

Reputation: 1261

Regex Optional char set in JavaScript

I wanted to validate the Name data files with following condition

So I tried the following Regex

    const regExp = /^[a-zA-Z0-9]+[a-zA-Z_-]+[a-zA-Z0-9]$/;

I need at least two characters, remaining are optional in the regExp everything works fine except this [a-zA-Z0-9] in the last, I want to make this optional

Upvotes: 1

Views: 99

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

You may consider using

/^(?=.{2})(?![^a-zA-Z]+$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*$/

See the regex demo

Details

  • ^ - start of string
  • (?=.{2}) - at least two chars
  • (?![^a-zA-Z]+$) - the string can't have no ASCII letter
  • [a-zA-Z0-9]+ - 1+ ASCII alnum chars
  • (?:[_-][a-zA-Z0-9]+)* - 0 or more sequences of _ or - followed with 1+ ASCII alnum chars
  • $ - end of string.

Upvotes: 1

Related Questions