Character classes and quantifiers in PHP - Time & Space Complexity
When using character classes and quantifiers in PHP regular expressions, it's important to understand how the matching process scales as the input grows.
We want to know how the time to find matches changes when the input string gets longer.
Analyze the time complexity of the following code snippet.
$pattern = '/[a-z]{3,5}/';
$input = str_repeat('abc', 1000);
if (preg_match_all($pattern, $input, $matches)) {
// matches found
}
This code searches for sequences of 3 to 5 lowercase letters in a long repeated string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The regex engine checks each position in the input string to see if the pattern matches.
- How many times: It tries to match starting at almost every character, so roughly once per character in the input.
As the input string gets longer, the regex engine does more checks, roughly one per character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the input size.
Time Complexity: O(n)
This means the time to find matches grows linearly as the input string gets longer.
[X] Wrong: "Using quantifiers always makes regex slow and exponential."
[OK] Correct: Simple quantifiers like {3,5} on character classes usually cause only linear checks, not exponential backtracking.
Understanding how regex matching time grows helps you write efficient patterns and explain your code clearly in interviews.
"What if we changed the quantifier from {3,5} to .*? How would the time complexity change?"
Practice
/[?]/Solution
Step 1: Understand character classes
In PHP regex,\\dmatches any digit (0-9),\\wmatches word characters,\\smatches whitespace, and\\Dmatches non-digits.Step 2: Identify the digit matcher
The class that matches digits is\\d.Final Answer:
\\d -> Option DQuick Check:
Digits = \\d [OK]
- Confusing \d with \w
- Using \D to match digits
- Mixing up \s with digit class
Solution
Step 1: Understand quantifiers
Curly braces{n}specify exact count.{3}means exactly 3 times.Step 2: Match exactly three lowercase letters
The pattern/[a-z]{3}/matches exactly three lowercase letters.Final Answer:
/[a-z]{3}/ -> Option AQuick Check:
Exact 3 lowercase letters = /[a-z]{3}/ [OK]
- Using {,3} which is invalid syntax
- Using {3,} which means 3 or more
- Using {3,5} which means 3 to 5 times
$pattern = '/\d{2,4}/';
$string = 'Year 2023 and 99 problems';
preg_match_all($pattern, $string, $matches);
print_r($matches[0]);Solution
Step 1: Understand the regex pattern
The pattern/\d{2,4}/matches sequences of digits between 2 and 4 digits long.Step 2: Apply pattern to string
In 'Year 2023 and 99 problems', '2023' (4 digits) and '99' (2 digits) match. Smaller digit groups like '2' or '3' alone do not match.Final Answer:
["2023", "99"] -> Option BQuick Check:
Digits 2-4 long = ["2023", "99"] [OK]
- Splitting digits into smaller groups
- Ignoring quantifier range
- Assuming single digits match
$pattern = '/[a-z]{2,1}/';Solution
Step 1: Analyze quantifier syntax
The quantifier{2,1}means minimum 2 and maximum 1 repetitions, which is invalid because min > max.Step 2: Confirm error type
Regex quantifiers must have min ≤ max. This causes a syntax error.Final Answer:
Quantifier range is invalid; min cannot be greater than max -> Option AQuick Check:
Min > max in {2,1} is invalid [OK]
- Swapping min and max values
- Ignoring quantifier syntax rules
- Assuming pattern is valid without checking quantifiers
Solution
Step 1: Understand the requirements
The string must start (^) with 3 to 5 uppercase letters[A-Z]{3,5}and end ($) with exactly 2 digits\d{2}.Step 2: Match pattern to options
/^[A-Z]{3,5}\d{2}$/ matches exactly 3-5 uppercase letters followed by exactly 2 digits, anchored start and end.Final Answer:
/^[A-Z]{3,5}\d{2}$/ -> Option CQuick Check:
3-5 uppercase + 2 digits = /^[A-Z]{3,5}\d{2}$/ [OK]
- Mixing digit counts in quantifiers
- Omitting anchors causing partial matches
- Using wrong quantifier ranges
Ready to prove it?
Pass the test and this pattern moves unknown
