I know the OP says it has to be a regex, but I agree with @tbodt’s comment above. This will accomplish what the OP is asking for without a regex and is posted here for anyone trying to solve a similar problem and is open to a different type of solution.
function everyAHasMatchingB(str) {
return Array.from(str)
.filter(c => c === 'A' || c === 'B')
.reduce((count, aOrB) => {
return aOrB === 'A' ? count + 1 :
count <= 0 ? NaN // Mismatched B. NaN ensures the function returns false.
: count - 1
}, 0) === 0;
}
solved Develop Regular Expression that every A is followed by a B