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

124
Visualizações
JavaScript - Regex with decimal values

I am trying to create a regular expression that validates an red/green/blue value expression. The expressions that I need my regular expression to match include:

  1. rgb(1, 10, 100)
  2. rgb(100, 10, 1)
  3. rgb(1,2,3)
  4. rgba(1, 2, 3, .75)
  5. rgba(1, 2, 3, 0.75)
  6. rgba(1, 2, 3, 0)
  7. rgba(1, 2, 3, 1)

Currently, I have the following regular expression:

^rgba?\((([+-]?\d+(\.\d+)?),\s*){2}[+-]?\d+(\.\d+)?(,\s*(0?\.\d|[01]))?\)$

This expression works for #1, #2, #3, #6, and #7. However, it fails for #4 and #5. I keep staring at the last group. To me, it looks like it should accept a decimal. Clearly, it's not though. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem in your regular expression, is that your expression doesn't allow for values greater than length 1 behind the last decimal point. Considering the original regular expession:

^rgba?\((([+-]?\d+(\.\d+)?),\s*){2}[+-]?\d+(\.\d+)?(,\s*(0?\.\d|[01]))?\)$

You will get a positive value for rgba(1, 2, 35.132, 0.7), but negative for rgba(1, 2, 35.132, 0.75).

The solution is adding a star to the last \d digit denotator, indicating that there can be any amount of digits. A plus would be even better, as it would detect faulty values that have 0 digits behind a decimal point, by requiring at least 1 of the \d instance.

^rgba?\((([+-]?\d+(\.\d+)?),\s*){2}[+-]?\d+(\.\d+)?(,\s*(0?\.\d*|[01]))?\)$
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