Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
How to write a regex matching word_char but only zero or one underscore

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?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

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
)

It can also be done without a lookahead but the length check of 4 or more characters becomes implicit instead of explicit. In other words, humans who read the pattern will need to determine the the minimum length of the string is 4 by understanding conditional expressions and summing the implemented quantifiers.

const tests = [
  'und',
  '_und',
  'u_nd',
  'un_d',
  'und_',
  'u_n_',
  'u__d',
  '8_no',
  'u_derscore',
  'un_erscore',
  'und_rscore',
  'unde_score',
  'under_co_e',
  'underscor_',
  '_nderscore'
];
for (i in tests) {
    document.write(tests[i] + ' => ' + /^[a-z](?:_[^\W_]{2,}|[^\W_]_[^\W_]+|[^\W_]{2,}_?[^\W_]+)$/i.test(tests[i]) + "<br>");
}

Breakdown:

/                        #pattern delimiter
^                        #start of string anchor
[a-z]                    #alphabetical character
(?:                      #non-capturing group
  _[^\W_]{2,}            #underscore, two or more alnum characters (at least 3 characters)
  |                      #or
  [^\W_]_[^\W_]+         #alnum character, underscore, one or more non-underscore (at least 3 characters)
  |                      #or
  [^\W_]{2,}_?[^\W_]+    #two or more alnum characters, optional underscore, one or more alnum characters (at least 3 characters)
)                        #end of non-capturing group
$                        #end of string anchor
/                        #pattern delimiter
i                        #case-insensitive pattern modifier
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda