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

176
Visualizações
Regex only allow dash in between characters

I have this regex ^[A-ZÆØÅa-zæøå\ \-]{2,50}$ for validating names. How can I make it allow only one "-". I want it to accept names like this:

Janet Smith-Johnson
Mary-Ann Johnson
Sara Mary John-Smith
Sara Johnson
Sara Mary Johnson

But it can't allow names that starts with - and ends with -. Like:

-Janet Mary
Mary-
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can match your character class without spaces, then optionally repeat a space and again use the character class without spaces.

Then optionally match - and the same mechanism again.

^(?=.{2,50}$)[A-ZÆØÅa-zæøå]+(?: [A-ZÆØÅa-zæøå]+)*(?:-[A-ZÆØÅa-zæøå]+(?: [A-ZÆØÅa-zæøå]+)*)?$

The pattern in parts matches:

  • ^ Start of string
  • (?=.{2,50}$) Assert 2 - 50 characters
  • [A-ZÆØÅa-zæøå]+ Match what is listed in the character class without a space
  • (?: [A-ZÆØÅa-zæøå]+)* Optionally repeat the character class preceded by a space
  • (?: Non capture group to match as a whole
    • -[A-ZÆØÅa-zæøå]+ Match what is listed in the character class without a space
    • (?: [A-ZÆØÅa-zæøå]+)* Optionally repeat the character class preceded by a space
  • )? Close the non capture group and make it optional
  • $ End of string

Regex demo

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use

^(?=.{2,50}$)(?!(?:.*-){2})[A-ZÆØÅa-zæøå]+(?:[- ][A-ZÆØÅa-zæøå]+)*$

See the regex demo.

If you are using the regex in C# or with u flag in JavaScript that supports ECMAScript 2018+ standard, you can also match any Unicode letter with \p{L}:

^(?=.{2,50}$)(?!(?:.*-){2})\p{L}+(?:[- ]\p{L}+)*$

Details:

  • ^ - start of string
  • (?=.{2,50}$) - two to fifty chars in the string allowed
  • (?!(?:.*-){2}) (or (?!(?:[^-]*-){2}) in the real code is more efficient) - no two hyphens are allowed
  • [A-ZÆØÅa-zæøå]+ - one or more letters from the set (\p{L} matches any Unicode letter)
  • (?:[- ][A-ZÆØÅa-zæøå]+)* - zero or more sequences of either space or - and then one or more letters
  • $ - end of string.
about 4 years ago · Juan Pablo Isaza 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