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

223
Visualizações
Regex pattern to match comments, but not URLs

I am trying to create a regex for detecting all the comments in a code. But I am also getting the hyperlinks because of the inline comment characters sequence //, which I don't want; I just need the comment part.

var sample = `Hello //this is a test
 http://google.com
 //second
 third
 https://test.com`;
var regex = new RegExp(
  /(\/\*([^*|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/g
);
console.log(sample.match(regex));

The output is ["//this is a test", "//google.com", "//second", "//test.com"]
The output should be ["//this is a test", "//second"]

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

0

For a quick and dirty way, you could use

(?<=^|[^\S])\/\/.+

See a demo on regex101.com.


In JavaScript, this could be

var sample = `Hello //this is a test
 http://google.com
 //second
 third
 https://test.com`;
var regex = new RegExp(/(?<=^|[^\S])\/\/.+/g);
console.log(sample.match(regex));

about 4 years ago · Juan Pablo Isaza Relatório

0

I added newline and 0 or more tabs before your two main capture groups:

/[\r\n][/t]*(\/\*([^*|[\r\n]|(\*+([^*\/]|[\r\n])))*\*\/)|[\r\n][\t]*(\/\/.*)/g

This means, the comment has to be at the beginning of a new line, so it wont match a hyperlink in the middle of your code.

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