Sheetal Mohan Sharma
Sheetal Mohan Sharma

Reputation: 2924

regex for alphanumieric string pattern with underscores and min occurannce and no max occurance - javascript

I am new to regex and trying validation in javascript/jquery using regex, appreciate any help.

The input is :

  1. alphanumeric string
  2. with minimum 3 underscores
  3. Underscores cannot be consecutive
  4. Underscores cannot just be separated by empty strings
  5. The string cannot start or end with an underscore

Valid test cases:

  1. Abc_def_gh_123
  2. Abc_def_1h_103_BA
  3. Abc_def_1h_103_BA

Invalid test cases

  1. ___
  2. _ _ _
  3. Abc_d
  4. Abc_def_ghi_de21_
  5. Abc_def_fg
  6. Abc_def_fg_
  7. _Abc_def_fg

I had tried regex in javascript

/^[a-zA-Z0-9]+_[a-zA-Z0-9]+_[a-zA-Z0-9]+_[a-zA-Z0-9]+$/

but it fails eg. if the string has more than 3 underscores

Upvotes: 2

Views: 155

Answers (3)

vks
vks

Reputation: 67978

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

Try this.This works.

See demo.

http://regex101.com/r/pP3pN1/5

Upvotes: 2

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14882

/([a-zA-Z0-9]+_[a-zA-Z0-9]+){3,}$/mg

http://regex101.com/r/yQ2xS9/2

Breakdown:

[a-zA-Z0-9]+ Starts with any number of lowercase and uppercase letters, or numbers.

_[a-zA-Z0-9]+ Contains an underscore followed by another sequence of lowercase/uppercase letters and numbers.

{3,}$ Minimum of three times (three lots of underscores)

Happy coding :)

Upvotes: 1

fabian
fabian

Reputation: 82461

This regexp should do the job:

/^([a-zA-Z0-9]+_){3,}[a-zA-Z0-9]+$/

Upvotes: 6

Related Questions