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

188
Visualizações
Why my regex is not matching all the substrings?

JS Code-

let N=7
let S="bab"


let arr=["a","b"]

for(i=2;i<N;i++){ //constructing a fibonnaci series
    let item=arr[i-1]+arr[i-2]
    arr.push(item)
}

// console.log(arr[N-1]) // babbababbabba

let marr=arr[N-1]

let str = new RegExp(S, "g");
let result=marr.match(str)

let answer=(result.length)
console.log(answer) // gives answer as 3 , but correct is 4

task at hand was to first construct a fibonnaci series where f1="a" and f2="b", For 3 onwards f3=f2+f1 and f4=f3+f2 Then we have to match the string S to see how many times it occurs in the fN. My code runs fine for rest of the test cases but for N=7 and S="bab" , correct answer is 4 but my code says 3.

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

0

Inspired by this answer, you can't do this with a single regex, but you can do this:

let results = [];
let match;
let N=7
let pat = /(?=(bab))\w/g;
let arr=["a","b"]

for(i=2;i<N;i++){ //constructing a fibonnaci series
    let item=arr[i-1]+arr[i-2]
    arr.push(item)
}

// console.log(arr[N-1]) // babbababbabba

let marr=arr[N-1]

while ( (match = pat.exec( marr ) ) != null ) { 
  results.push( match[1] );
}

console.log(results.length);

You capture all three digits inside the lookahead, then go back and match one character in the normal way just to advance the match position.

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