Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!