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

417
Visualizações
RegEx: If first character is '%' or alphanumeric then

in nodejs, I have to following pattern

(/^(>|<|>=|<=|!=|%)?[a-z0-9 ]+?(%)*$/i

to match only alphanumeric strings, with optional suffix and prefix with some special characters. And its working just fine.

Now I want to match the last '%' only if the first character is alphanumeric (case insensitive) or also a %. Then its optionally allowed, otherwise it should not match.

Example:

Should match:

>test
!=test
<test
>=test
<=test
%test
test
%test%
test%

Example which should not match:

<test% <-- its now matching, which is not correct
<test< <-- its now **not** matching, which is correct

Any Ideas?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can add a negative lookahead after ^ like

/^(?![^a-z\d%].*%$)(?:[><]=?|!=|%)?[a-z\d ]+%*$/i
  ^^^^^^^^^^^^^^^^^  

See the regex demo. Details:

  • ^ - start of string
  • (?![^a-z\d%].*%$) - fail the match if there is a char other than alphanumeric or % at the start and % at the end
  • (?:[><]=?|!=|%)? - optionally match <, >, <=, >=, != or %
  • [a-z\d ]+ - one or more alphanumeric or space chars
  • %* - zero or more % chars
  • $ - end of string
over 4 years ago · Santiago Trujillo Relatório

0

You might use an alternation | to match either one of the options.

^(?:[a-z0-9%](?:[a-z0-9 ]*%)?|(?:[<>]=?|!=|%)?[a-z0-9 ]+)$
  • ^ Start of string
  • (?: Non capture group
    • [a-z0-9%] Match one of the listed in the character class
    • (?:[a-z0-9 ]*%)? Optionally match repeating 0+ times any of the character class followed by %
    • | Or
    • (?:[<>]=?|!=|%)? Optionally match one of the alternatives
    • [a-z0-9 ]+ Match 1+ times any of the character class
  • ) Close non capture group
  • $ End of string

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