Named captures in PowerShell - Time & Space Complexity
We want to understand how the time it takes to find named captures in text grows as the text gets longer.
How does the script's work increase when the input text size changes?
Analyze the time complexity of the following code snippet.
$text = "Name: John, Age: 30; Name: Alice, Age: 25"
$pattern = '(?<name>\w+), Age: (?<age>\d+)'
foreach ($match in [regex]::Matches($text, $pattern)) {
$name = $match.Groups['name'].Value
$age = $match.Groups['age'].Value
Write-Output "Name: $name, Age: $age"
}
This code finds all name and age pairs in the text using named captures and prints them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each match found in the text.
- How many times: Once for each matched name-age pair in the input text.
As the input text grows, the number of matches usually grows roughly in proportion to the text length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 to 2 matches processed |
| 100 | About 10 to 20 matches processed |
| 1000 | About 100 to 200 matches processed |
Pattern observation: The work grows roughly in direct proportion to the input size.
Time Complexity: O(n)
This means the time to find and process named captures grows linearly as the input text gets longer.
[X] Wrong: "Named captures make the search much slower because they add extra work."
[OK] Correct: Named captures just label parts of the match; the main work is still scanning the text once, so the time grows linearly with input size.
Understanding how pattern matching scales helps you write scripts that handle bigger data smoothly and shows you can think about efficiency clearly.
"What if the pattern was more complex and used nested groups? How would the time complexity change?"