Single match
suggest changeYou can quickly determine if a text includes a specific pattern using Regex. There are multiple ways to work with Regex in PowerShell.
#Sample text
$text = @"
This is (a) sample
text, this is
a (sample text)
"@
#Sample pattern: Content wrapped in ()
$pattern = '\(.*?\)'
Using the -Match operator
To test a string against a pattern, use the -match operator: 'input' -match 'pattern'. It returns $true or $false. After a successful match, $Matches holds the match and any groups defined in the pattern. -match on one string returns only the first match.
> $text -match $pattern
True
> $Matches
Name Value
---- -----
0 (a)
You can also use -match to filter through an array of strings and only return the strings containing a match.
> $textarray = @"
This is (a) sample
text, this is
a (sample text)
"@ -split "`n"
> $textarray -match $pattern
This is (a) sample
a (sample text)
Using Select-String
Select-String searches text with a regex. It returns a MatchInfo object for each input that contains a match. Its properties include the matching groups. Without -AllMatches, only the first match in each input is returned.
> $m = Select-String -InputObject $text -Pattern $pattern
> $m
This is (a) sample
text, this is
a (sample text)
> $m | Format-List *
IgnoreCase : True
LineNumber : 1
Line : This is (a) sample
text, this is
a (sample text)
Filename : InputStream
Path : InputStream
Pattern : \(.*?\)
Context :
Matches : {(a)}
Like -match, Select-String can also be used to filter through an array of strings by piping an array to it. It creates a MatchInfo-object per string that includes a match.
> $textarray | Select-String -Pattern $pattern
This is (a) sample
a (sample text)
#You can also access the matches, groups etc.
> $textarray | Select-String -Pattern $pattern | fl *
IgnoreCase : True
LineNumber : 1
Line : This is (a) sample
Filename : InputStream
Path : InputStream
Pattern : \(.*?\)
Context :
Matches : {(a)}
IgnoreCase : True
LineNumber : 3
Line : a (sample text)
Filename : InputStream
Path : InputStream
Pattern : \(.*?\)
Context :
Matches : {(sample text)}
Select-String can also search using a normal text-pattern (no regex) by adding the -SimpleMatch switch.
Using [RegEx]::Match()
You can also use the static Match() method of the .NET [regex] class. It returns the first match.
> [regex]::Match($text,$pattern)
Groups : {(a)}
Success : True
Captures : {(a)}
Index : 8
Length : 3
Value : (a)
> [regex]::Match($text,$pattern) | Select-Object -ExpandProperty Value
(a)