Regex test but only when 11 characters

Viewed 106

I have the javascript regex /^[a-zA-Z]{6}[a-zA-Z0-9]{5}$/ but I would also like the test to pass if the string is less than or greater than 11 characters. So any string from 0-10 characters would pass, any string 12 or greater characters would pass, but if it is exactly 11 characters it will be evaluated by the previously mentioned test.

1 Answers

You can use

/^(?:.{0,10}|.{12,}|[a-zA-Z]{6}[a-zA-Z0-9]{5})$/

See the regex demo.

Details

  • ^ - start of string
  • (?:
    • .{0,10} - zero to ten chars other than line break chars
    • | - or
    • .{12,} - twelve or more chars other than line break chars
    • | - or
    • [a-zA-Z]{6}[a-zA-Z0-9]{5} - six letters and then five alphanumeric chars
  • ) - end of the group
  • $ - end of string.

To also match line break chars, you may add the /s flag (if you are using the ECMAScript 2018 compliant JavaScript environment) or replace each . with [\w\W] / [\s\S] / [\d\D] / [^].

Related