Without anchors your regex will not be limited to a fixed number of characters

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the regex category.

Last Updated: 2024-11-21

I wanted to write a validation for JSON youtube_ids. These YouTube ids looked like this: "aKXlZz-wbmg"

I came up with the following regex on 1st try:

{
  "pattern": "[0-9a-zA-Z-]{11}"
}

Sadly, my regex was not strict enough: Because it did not include anchors, it also matched for longer strings, ones with more than 11 characters:

e.g. "aaaaaaaaaaaaaaaaaaaaaaasdfasaa".match("[0-9a-zA-Z-]{11}") gives true.

The solution was to add anchors for the first and last character

{
  "pattern": "^[0-9a-zA-Z-]{11}$"
}

Lesson

Even if your regex if for a fixed number of characters, the lack of anchors means it will match at least that number of characters.