...

/

Analyzing Different Types of Regular Expressions

Analyzing Different Types of Regular Expressions

Learn and practice different types of regular expressions.

Character classes

A character class allows us to specify which characters are acceptable for any given position. For example, suppose we had the following pattern:

/abc/

We can interpret it as a literal a followed by a literal b followed by a literal c. Suppose we wanted to match all substrings that contained those three characters in any order. We can achieve this using a character class. We define character classes by specifying what characters are allowed between square brackets:

Press + to interact
<?php
$text = 'aaa abc acc cba';
// Returns ["aaa", "abc", "acc", "cba"]
str($text)->matchAll(
'/[abc][abc][abc]/'
)->all();

We can also use negation to specify that we do not want characters to appear at a specific location. We do this by starting our class with the ^ character:

Press + to interact
<?php
$text = 'aaa abc def cba';
// Returns ["aaa"]
str($text)->matchAll(
'/[abc][^be][abc]/'
)->all();

In the code above, our regular expression can be interpreted as:

  • The character a, b, or c followed by
    • Any character that is not b or e`, followed by
      • The character a, b, or c.

If we wanted to include the ^ character itself in our character class, we need to add it to the end of the character class so it is not interpreted as the negation operator:

Press + to interact
<?php
$text = 'aaa abc a^b cba';
// Returns ["a^b"]
str($text)->matchAll(
'/[abc][z^][abc]/'
)->all();

We can also specify ranges of characters when defining our character classes. This helps to avoid having to write every possible combination of characters. For example, we could rewrite our ...