The rules for this test are:
Number sign (#)
Minus (-)
Full stop (.)
Slash (/)
Space ( )
Examples of desired matches:
445b
apt 445a
Apt. #445
Apt 445
Apt-445
Apt - 445
apt445
apt#445
apt/445
APT-445a
APT - 445c
Apt# 445b
Apt. #445-c
22 Elm St.
Examples of non-matches:
apt four forty five
Elm St.
Elm St
Elm Street
445
445 445
445-445
#445
(any or all of the special characters by themselves)
41686d6564's answer below is extremely close but in my original question I failed to specify that spaces are part of the special characters:
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9\-#\.\/]+$/
I've tried on my own to get the space special character incorporated but I don't get the desired outcome.
See the live example. Live Example
This regex validates your rules:
/^(?=.*[A-Za-z])(?=.*\d)(?!.*[^A-Za-z0-9\-#\.\/])/
Explanation:
^
- start of string(?=.*[A-Za-z])
- positive lookahead for at least one alpa char(?=.*\d)
- positive lookahead for at least one digit char(?!.*[^A-Za-z0-9\-#\.\/])
- negative lookahead for any not allowed charInstead of the double negative you could use a pattern looking for all valid chars until end of string:
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9\-#\.\/]*$/
UPDATE based on updated requirement to allow spaces:
/^(?=.*[A-Za-z])(?=.*\d)(?!.*[^A-Za-z0-9\-#\.\/ ])/
Explanation: Simply add a space to the negated character class
Alternatively, look for all valid chars, including space:
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9\-#\.\/ ]*$/
UPDATE, with JavaScript tests:
const tests = `445b
apt 445a
Apt. #445
Apt 445
Apt-445
Apt - 445
apt445
apt#445
apt/445
APT-445a
APT - 445c
Apt# 445b
Apt. #445-c
22 Elm St.
apt four forty five
Elm St.
Elm St
Elm Street
445
445 445
445-445
#445`;
var regex = /^(?=.*[A-Za-z])(?=.*\d)(?!.*[^A-Za-z0-9\-#\.\/ ])/;
tests.split(/[\r\n]+/).forEach((str) => {
result = regex.test(str);
console.log(str + ' ==> ' + result);
});