Home > Blockchain >  How to write a regex matching word_char but only zero or one underscore
How to write a regex matching word_char but only zero or one underscore

Time:04-10

I have a username to test:

  1. it is made up of at least 4 characters
  2. it can contain only word character, number, and underscore (max. one time)
  3. it should start with a word character and it cannot end with an underscore.

I have written this regex

^[a-zA-Z][^\W_]{2,}_?[a-zA-Z0-9]$

But I really have no idea how to limit the appearance of underscore (0-1 times).

How can I achieve my requirements?

CodePudding user response:

Use a lookahead to check the more-specific qualifications, then apply the general rule of \w{4,}.

Regex101 Demo

const tests = ['_und', 'u_nd', 'un_d', 'und_', 'u_n_', 'u__d', '8_no'];
for (i in tests) {
    document.write(tests[i]   ' => '   /^(?=[a-z][^_]*_?[^_] $)\w{4,}$/i.test(tests[i])   "<br>");
}

(?=         #lookahead
  [a-z]     #a letter
  [^_]*     #zero or more non-underscores
  _?        #an optional underscore
  [^_] $    #one or more non-underscores until the end of the string
)

CodePudding user response:

https://rubular.com/r/7AApDKT3BSU3BR

The _? limits the _ to zero or more, you can test above, looks like you meet all your requirements?

  • Related