Powershell regex multiline

PowerShell Regex Multiline

PowerShell supports multiline regular expressions using the [\s\S] pattern or the (?s) inline modifier. These techniques allow you to match patterns across multiple lines of text, which is especially useful when dealing with block comments, logs, or multi-line strings.

Example 1: Using the [\s\S] Pattern

In this example, we will use the [\s\S] pattern to match a multiline string enclosed within /* */ block comments:

$text = @"
/* This is a multiline
   string within block comments */
"@

$regex = [regex]"/\*([\s\S]*?)\*/"
$matches = $regex.Match($text)
$matches.Groups[1].Value

Output:

This is a multiline
   string within block comments

The [regex]"/\*([\s\S]*?)\*/" regex pattern looks for a /* followed by any number of characters, including newline characters ([\s\S]), until the first occurrence of */. The (?s) inline modifier is not required in this case. The $matches.Groups[1].Value statement retrieves the matched text within the first captured group.

Example 2: Using the (?s) Inline Modifier

In this example, we will use the (?s) inline modifier to match a multiline log message starting with [ERROR]:

$log = @"
[INFO] Log message 1
[ERROR] This is a multiline
        log message
[INFO] Log message 2
"@

$regex = [regex]"(?s)\[ERROR\]([\s\S]*?)\[INFO\]"
$matches = $regex.Match($log)
$matches.Groups[1].Value

Output:

This is a multiline
        log message

The [regex]"(?s)\[ERROR\]([\s\S]*?)\[INFO\]" regex pattern matches the text starting with [ERROR], followed by any number of characters ([\s\S]), until the first occurrence of [INFO]. The (?s) inline modifier is used to enable the “single-line mode”, where the dot (.) character matches any character including newline characters. Again, the $matches.Groups[1].Value statement is used to retrieve the matched text within the first captured group.

These examples demonstrate two different approaches to handle multiline regex in PowerShell. Choose the technique that best suits your specific use case.

Leave a comment