Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Testing regular expressions


In this recipe, we are going to explore some ways to use and test regular expressions.

How to do it...

Let's check out regular expressions in PowerShell:

  1. Open PowerShell ISE as an administrator.

  2. Add the following script and run it:

    $VerbosePreference = "Continue"
    
    #check if valid email address
    $str = "[email protected]"
    $pattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|gov|ca|mil|biz|info|mobi|name|aero|jobs|museum)$"
    
    if ($str -match $pattern)
    {
       Write-Verbose "Valid Email Address"
    }
    else
    { 
      Write-Verbose "Invalid Email Address"
    }
    
    #another way to test 
    [Regex]::Match($str, $pattern)
    
    #can also use regex in switch
    $str = "V1A 2V1"
    $str = "90250"
    
    switch -regex ($str)
    {
       "(^\d{5}$)|(^\d{5}-\d{4}$)" 
       { 
            Write-Verbose "Valid US Postal Code" 
       }
       "[A-Za-z]\d[A-Za-z]\s*\d[A-Za-z]\d"
       {
            Write-Verbose "Valid Canadian Postal Code" 
       }
       default 
       { 
            Write-Verbose "Don't Know" 
       }
    }
    
    #use regex and extract matches...