Powershell :- Regular Expression – Using [regex]::matches

Background

In our last post spoke about using the match operator to issue Regular Expression calls.

Lineage

  1. PowerShell :- Regular Expression
    Link

RegEx Class

The -Match operator is a bit restrictive in terms of flexibility and so it is likely better to utilize the RegEx Class.

Outline

  1. Access RegEx Class Match operator
    • The first operand is the text
    • The second operator is the pattern
    • And, the third is RegEx Options
      • In our case, ignorecase
  2. Result is sent back as a collection
    • Specifically System.Text.RegularExpressions.MatchCollection
    • Simple access using index suffixes for our case

Code



Set-StrictMode -version 2

[string] $regExpPattern=$null;
[string] $fullname=$null;
[int]    $iNumberofMatches=0;
[hashtable] $obListofNames =$null;
[object] $objRegEx =$null;
[string] $listofNamesType = $null;
[int]    $iElementID = 0;
[string] $log=$null;
[string] $regExpOption=$null;
[Boolean] $debug = $false;
#[Boolean] $debug = $true;

# Regular Expression
$regExpPattern="(\w+)(\w+)";

# Regular Expression Option
$regExpOption="IgnoreCase";

$fullname="Daniel Adeniji"


$objListofNames = ( [regex]::matches( `
                                          $fullname `
                                        , $regExpPattern `
                                        , $regExpOption`
                                        ) `
                  )

if ($objListofNames)
{

    if ($debug)
    {

        
        $log = "[regex]::expression is {0} " -f $regExpPattern;

        Write-Host($log);

        
        $listofNamesType = $objListofNames.GetType();

        $log = "[regex]::matches return type is {0} " -f $listofNamesType;

        Write-Host($log);

    }

    
    $iNumberofMatches = $objListofNames.Count;

    $log = "Number of Matches is {0}" -f $iNumberofMatches;

    Write-Host($log);

    if ($iNumberofMatches -gt 0)
    {

        $log = "First name is {0}" -f $objListofNames[0];

        Write-Host($log);

    }

    if ($iNumberofMatches -gt 1)
    {

        $log = "Last name is {0}" -f $objListofNames[1];

        Write-Host($log);

    }   

}
else
{
    Write-Host "$objListofNames is null"
}

Output

regex.matches.output.20190406.0935AM

References

  1. Microsoft
    • System.Text.RegularExpressions
      • Regex.Matches Method

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s