Home > OS >  Match across line breaks when using -match with a regular expression
Match across line breaks when using -match with a regular expression

Time:12-02

The following results a single match of "foo".

$multilineString = "foo
    bar
         baz";

$multilineString -match ".*";

$matches;

That is because the . character does not include line breaks.

These also output only "foo".

$multilineString -match "(.|\r)*" | Out-Null; $matches[0];
$multilineString -match "(.|\r\n)*" | Out-Null; $matches[0];

In PowerShell, how do we use match to include any character including line breaks, so that the output will include all three lines:

foo
bar
baz

CodePudding user response:

I almost never use -match for this specific use, as in my comment, I usually go with [regex]. After reviewing the MS Docs:

It is important to note that the $Matches hashtable contains only the first occurrence of any matching pattern.

So, if you want to get the same result as [regex]::Matches($multilineString, '\w ').Value, that would require first to split the string and then loop over it:

$multilineString = "foo
    bar
         baz"

$multilineString -split '\r?\n' | ForEach-Object {
    if($_ -match '\w ')
    {
        $Matches
    }   
}
Name                           Value
----                           -----
0                              foo
0                              bar
0                              baz

An alternative that would also work and will not require a split or a loop is possible, but the regex pattern has to be more specific. In this case, we know that we're looking for 3 words.

$multilineString = "foo
    bar
         baz"

$multilineString -match '^(\w )\s (\w )\s (\w )$'
$Matches
Name                           Value
----                           -----
3                              baz
2                              bar
1                              foo
0                              foo…
  • Related