Search code examples
javascriptregexstreet-address

Street address regex for JavaScript


The rules for this test are:

  1. Must contain letters and numbers
  2. May contain these special characters anywhere within the string:
Number sign (#)
Minus (-)
Full stop (.)
Slash (/)
Space ( )
  1. May not contain any other special characters
  2. May not consist of only letters
  3. May not consist of only letters and/or the special characters
  4. May not consist of only numbers
  5. May not consist of only numbers and/or the special characters
  6. The numbers, letters and special characters may be in any order

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


Solution

  • 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 char

    Instead 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);
    });