Pattern matching

Sometimes you will need to create extension patterns in your dialplan that match more than one possible dialed number. We had that kind of a situation in the previous section, when we needed to match any 4-digit number. Extension patterns saves us from having to create an extension in the dialplan for every possible number that might be dialed.

Patterns always begin with an underscore (_). This symbol tells Asterisk that the extension is a pattern and not the name of an extension (remember, extensions don’t have to be just numbers!). After the underscore symbol, we use various character to represent sets or ranges of numbers:

  • X – represents any single digit from 0 to 9.
  • Z – represents any single digit from 1 to 9.
  • N – represents any single digit from 2 to 9.
  • [x-y] – represents a single character from the range of digits specified. For example, [3-6] matches 3,4,5, or 6.
  • . – the period matches one or more characters. It is usually placed at the end of a pattern when you need to match extensions of an indeterminate length.

Here is a simple example that shows how pattern matching can make our dialplan more compact and elegant. Le’ts say that we have the extensions 950 through 959 that do the same thing – play the hello-world sound. Without pattern matching, our dialplan would look something like this:

[local]
exten => 950,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 951,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 952,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 953,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 954,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 955,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 956,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 957,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 958,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

exten => 959,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

The code above would work fine, but we can shorten the dialplan using pattern matching to make the dialplan shorter:

[local]
exten => _95X,1,Answer()
 same => n,Playback(hello-world)
 same => n,Hangup()

Now, we’ve specified the pattern of _95X. As mentioned above, the _ symbol tells Asterisk that the extension is a pattern, 95 represent the first two numbers of the extension, and the X character represents any number from 0-9.

The pattern specified above (_95X) will match only three-digits extensions! For example, the extensions 9555 or 95 will not be matched. To match the 9555 extension, the _95X. extension could be used.
Geek University 2022