How to Extract Delimited Text with a Lazy Regular Expression

For simple, non-nested delimiters, a lazy quantifier stops each match at the next valid closing delimiter. In .*?, the question mark makes * lazy. It does not mean “zero or one character” in that position.

Extract every section

PowerShell
$text = "BEGINfirstEND ignored BEGINsecond`nlineEND"
$pattern = 'BEGIN(?<value>.*?)END'
$sections = [regex]::Matches(
    $text,
    $pattern,
    [Text.RegularExpressions.RegexOptions]::Singleline,
    [TimeSpan]::FromSeconds(1)
)

$sections | ForEach-Object { $_.Groups['value'].Value }

The output is first, then a second value containing second, a newline and line. Singleline lets the dot match newline characters. It does not change how anchors work. Without that option, a multi-line section would not match this pattern.

Compare greedy and lazy behavior

Change .*? to .* and repeat. The greedy version can absorb both sections, ending at the last END. The lazy version yields the nearest closing delimiter that allows the match to succeed.

The literal delimiters here are BEGIN and END. When delimiter text comes from configuration, construct the pattern with [regex]::Escape($opening) and [regex]::Escape($closing) so punctuation is not treated as regex syntax.

Define malformed-input behavior

A section with no closing delimiter is not returned by this pattern. Empty sections are returned as empty strings because * permits zero characters. Decide whether those cases are acceptable before treating extracted values as validated data.

This expression does not parse nested or escaped delimiters. Use the format's parser when the input is XML, JSON, a programming language or another structured grammar. Keep a bounded input size and an explicit match timeout for untrusted text. A timeout is an error to handle, not an empty-match result.

References

Quantifiers in Regular Expressions - .NET
Learn about regular expression quantifiers, which specify how many instances of a character, group, or character class must be present in the input to match.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions
Regular-expression quantifiers
Options for regular expression - .NET
Learn how to use regular expression options in .NET, such as case-insensitive matching, multiline mode, and right-to-left mode.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options
Regular-expression options

Author: Herman Schoenfeld