Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda