Inverting Character Sets in Regex

Using the caret ^ at the beginning of square brackets allows you to invert the desired set. That is, if, for example, the pattern [ab] searches for the letter 'a' or 'b', then the pattern [^ab] will search for all characters except 'a' and 'b'.

Example

In this example, the search pattern looks like this: letter 'x', then NOT letter 'a', not 'b' and not 'c', then letter 'z':

php<?php
  $str = 'xaz xbz xcz xez';
  $res = preg_replace('#x[^abc]z#', '!', $str);
?>

As a result, the following will be written to the variable:

php'xaz xbz xcz !'

Example

In this example, the search pattern looks like this: letter 'x', then NOT a lowercase Latin letter, then letter 'z':

php<?php
  $str = 'xaz xbz x1z xCz';
  $res = preg_replace('#x[^a-z]z#', '!', $str);
?>

As a result, the following will be written to the variable:

php'xaz xbz ! !'

Practice Tasks

Задание 1

Write a regular expression that finds strings matching the pattern: digit '1', then a character that is not 'e' and not 'x', digit '2'.

Задание 2

Write a regular expression that finds strings matching the pattern: letter 'x', then NOT a digit from 2 to 7, letter 'z'.

Задание 3

Write a regular expression that finds strings matching the pattern: letter 'x', then NOT an uppercase Latin letter from 1 or more times, letter 'z'.

Задание 4

Write a regular expression that finds strings matching the pattern: letter 'x', then not an uppercase and not a lowercase Latin letter and not a digit from 1 to 5 from 1 or more times, letter 'z'.