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

319
Visualizações
PHP Regex: allowed no more 3 digits but any count for another chars

I need to modify the exp:

/^[-\p{L}\d]+$/u

The purpose is to allow maximum 3 digits in whole string, but letter chars and dashes should be allowed without quantity restrictions. No matters where digits are located within string. For instance:

test345  //this should match
345te-st  //this should match
3454dtest  //this shouldn\'t match

I have already tried some patterns, but is don't work properly:

/^[-\p{L}\d{0,3}]+$/u
/^[-\p{L}]+[\d]{0,3}+$/u
/^([-\p{L}]+)([\d]+){0,3}$/u
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The patterns that you tried don't work properly matching max 3 digits anywhere in the string because between the start and end anchors:

  • This notation is fully in a character class [-\p{L}\d{0,3}]+ which matches repeating 1+ times any of the listed characters between [...] (So there is no digit limit due to the +)
  • This notation [-\p{L}]+[\d]{0,3}+ matches 1+ times [-\p{L}] followed by 0-3 consecutive digits (So the digits can not be at the start for example)
  • This notation ([-\p{L}]+)([\d]+){0,3} uses 2 capture groups, but the order here is also 1+ times [-\p{L}] and 0-3 consecutive digits (only here is the capture group repeated)

If empty strings are also allowed:

^(?:[\p{L}-]*\d){0,3}[\p{L}-]*$
  • ^ Start of string
  • (?:[\p{L}-]*\d){0,3} Match 0-3 times optional repetitions of [\p{L}-] and a single digit
  • [\p{L}-]* Match optional repetitions of [\p{L}-] at the end
  • $ End of string

Regex demo

Else you can assert that the string is not empty using (?!$)

^(?!$)(?:[\p{L}-]*\d){0,3}[\p{L}-]*$

Regex demo

over 4 years ago · Santiago Trujillo 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