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

143
Visualizações
Regex to match multiple variations with lookbehind conditionals and being DRY

In JavaScript, I'm trying to match the following samples to capture just src/ for a find and replace that is iterating over HTML and CSS files.

Samples to match:

1. url(src/imgs/...)
2. url("src/imgs/...")
3. url('src/imgs/...')
4. <img src="src/imgs/...">

I'm trying to not repeat in the Regex and don't want multiple groups with almost identical expressions.

I created a non-capture group and I'm able to match 1 & 4 but it does not match 2 & 3.

(((?<=url\()(?<=['"])?)|(?<=\<img\ssrc="))src\/

I can't figure out how to capture all 4 groups in a DRY way without optional quantifiers - which aren't supported in non-capture groups.

A less elegant Regex like below will work.

((?<=url\()|(?<=url\(['"])|(?<=\<img\ssrc="))src\/

Is there a more elegant solution than using two groups to account for variations in the samples 1 to 3?

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

0

Extracting data from the CSS and HTML source with regexp does not look like a good idea. There are special parsers for that. Though here's the code you might find helpfull:

var samples = [
  'url(src/imgs/...)',
  'url("src/imgs/...")',
  'url(\'src/imgs/...\')',
  '<img src="src/imgs/...">',
  '<img src=\'src/imgs/...\'>',
  '<img src=\'src/imgs/...\' alt=\'\'>',
];

var report = [];

var re = new RegExp(
  '(?:'                   // prefix is
    + '(?:url\\()'        // 'url('
    + '|'                 // or 
    + '(?:<img\\s+src=)'  // '<img src='
  + ')'
  + '([\'"]?)'            // followed by an optional quote
  + '(.*?)'               // URL itself
  + '\\1'                 // followed by the quote (still optional)
  + '\s?.*'               // 'img' specific optional suffix (other attributes)
  + '[)>]'                // enclosed by a '>' or a ')' symbol
);

samples.forEach(function( sample ){

  report.push( 
    re.exec(
      sample
    ).join("\t\t")
  );

})

console.log(report.join("\n"));

Output:

url(src/imgs/...)               
url("src/imgs/...")     "       src/imgs/...
url('src/imgs/...')     '       src/imgs/...
<img src="src/imgs/...">        "       src/imgs/...
<img src='src/imgs/...'>        '       src/imgs/...
<img src='src/imgs/...' alt=''>     '       src/imgs/...

Note, that this will fail for images with unquoted src like this: <img src=src/imgs/...>

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