skip to Main Content

I want regex to match either a-z or 0-9 characters of any length any order or exact string N/A.

Matching and nonmatching examples are below:

  1. N/A – match

  2. asd6fg – match

  3. 123asd – match

  4. asd234 – match

  5. 12sd23 – match

  6. as23fd – match

  7. NA – no match

  8. N/AN/A – no match

  9. N/ – no match

  10. N – no match

  11. 123N/A – no match

  12. abcN/A – no match

  13. a1bN/A – no match

  14. N/Aab2 – no match

  15. AS123 – no match

2

Answers


  1. This should do it:

    ^(?:[a-zd]+|N/A)$
    

    ^ inidicates the start of input , (?:...) creates a non-capturing group; then either [all lowercase letters and digits]+ or| N/A are matched. $ marks the end of input

    Login or Signup to reply.
  2. Just use this:

    ^([a-z0-9]+|N/A)$
    

    Explanation:

    • ^ and $ say indicate the start and end of the string, respectively. By putting these at the ends of the RegEx, you’re saying that it should only match if it can match everything. It’s all or nothing.
    • [a-z0-9]+ will match a-z and 0-9 one or more times.
    • | is the logical OR. It will either match the thing before it ([a-z0-9]+) or the thing after it, which is…
    • N/A which is the exact string "N/A". You need to escape that / character.

    Example:

    const regex = /^([a-z0-9]+|N/A)$/;
    
    // match
    console.log(regex.test('N/A'));
    console.log(regex.test('123abc'));
    console.log(regex.test('abc123'));
    
    // don't match
    console.log(regex.test('N/AN/A'));
    console.log(regex.test('123ABC'));
    console.log(regex.test('ABC123'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search