const regex = /(?!(.*(?:[ -\/:-@[-`{-~À-ÿ].*){4}))^[A-Za-z\d -\/:-@[-`{-~À-ÿ]{8,30}$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?!(.*(?:[ -\\\/:-@[-`{-~À-ÿ].*){4}))^[A-Za-z\\d -\\\/:-@[-`{-~À-ÿ]{8,30}$', 'gm')
const str = `AABBCCDD
OK -- Match
aabbccdd
OK -- Match
11111111
OK -- Match
A1A1b2b2
OK -- Match
A@~D1dIo
OK -- Match
AAB BCC0
OK -- Match (1 special, it's okay)
AABBCC@@
OK -- Match (2 specials, it's okay)
AABB C
OK -- Match (3 specials, it's okay)
A@~\` C:
OK -- Match (3 specials, it's okay)
AABB
OK -- Should't match and didn't match (Less than 8 symbols)
AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP
OK -- Should't match and didn't match (More than 30 symbols)
AA@@@@BB
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
AAB B
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
AABB@@@@
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions