PowerShell :- Regular Expression

 

Background

Looking at a useful tool written in PowerShell.

But, it was fading.

Time to play around with Regular Expression, Regex.

Code

Powershell

Objective

  1. Prepare Regular Expression
    • In our case, stored in $regexp
  2. Prepare Input
    • In our case, store in $fullname
  3. Issue RegEx call using -match operator
  4. Results is saved in Hashtable
    • The name of the system populated Hashtable is $hashtable
      • The 0th element is the passed in input
      • 1 is the first match
      • 2 is the second match
      • And, on and on

Implementation


Set-StrictMode -version 2

[string] $regexp=$null;
[string] $fullname=$null;
[int]    $iNumberofMatches=0;
[hashtable] $obListofNames =$null;

$regexp="(\w+) (\w+)";
$fullname="Daniel Adeniji"

$fullname -match $regexp  | Out-Null;

$obListofNames = $Matches;

$iNumberofMatches = $obListofNames.Count-1;

Write-Host("Number of matches :- " + $iNumberofMatches);

if ($obListofNames)
{
    Write-Host("Full Name :- " + $obListofNames[0]);
}

if ($iNumberofMatches -gt 0)
{
    Write-Host("First Name :- " + $obListofNames[1]);
}

if ($iNumberofMatches -gt 1)
{
    Write-Host("Last Name :- " + $Matches[2]);
}

Output

powershell.regex.20190405.0348PM

One thought on “PowerShell :- Regular Expression

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