Table of Contents
Using Regular Expression
We use regular expressions whenever we are required to look for specific patterns in the text. The regular expressions, also known as regex
, comprise operators, literal characters, and other constructs. PowerShell has various cmdlets and operators that allow us to use regex with them; some of them are given below:
- Using
-match
Operator - Using
-split
Operator - Using
Select-String
Cmdlet - Using
switch
Statement with-Regex
Option
We can also use the -like
operator, but it does not work with regular expressions. We will see how to use it in our case. Let’s learn each of them below.
Use -match
Operator
Use the -match
operator to check if the specified string contains the number.
1 2 3 4 5 6 7 8 9 |
$string = "It is a sample string containing 0123 numbers." if ($string -match "\d+") { Write-Host "The string has number(s)." }else{ Write-Host "The string does not has number(s)." } |
1 2 3 |
The string has number(s). |
First, we defined a variable named $string
and initialized it with a string value containing a numeric value. Next, we used the if
statement with the -match
operator and a regex (\d+
) to check if the $string
contained any numbers and returned True
if it contained. As a result, the if
statement became True
, which executed the if
block; otherwise, the else
block would be executed. Finally, we used Write-Host cmdlet to display a customized message to let the user know if the number found in the $string
.
Here,
\d
will only match with numbers including decimal points regardless of the decimal’s position, which means01.23
,.0123
, and0123.
all will be detected. At the same time,+
would match one or multiple instances of the numbers.
Use -like
Operator
Use the -like
operator to determine if the string contains the number.
1 2 3 4 5 6 7 8 9 |
$string = "It is a sample string containing 0123 numbers." if ($string -like "*[0-9]*") { Write-Host "The string has number(s)." }else{ Write-Host "The string does not has number(s)." } |
1 2 3 |
The string has number(s). |
This example is similar to the previous one, but we used the -like
operator, which does not support regular expressions. Still, we can use this operator to check if $string
contains the number using patterns matching. Here, the *[0-9]*
matched the string containing one or multiple numbers. The -like
operator also returns True
if the match is found, which causes the if
block’s execution; else, the else
part would be executed.
Use -split
Operator
To check if the string contains the number(s):
- Define a string with numbers in it.
- Use the
-split
operator with\D+
regex to match one or multiple non-digit characters, resulting in an array having sequences of numbers. - Use the
foreach
loop to iterate over the array containing sequences of numbers that we received in the previous step. - In each iteration:
- Use the
if
statement with the-match
operator and a regex (\d+
) to check if it contains the number - Use the
Write-Host
cmdlet if theif
condition is satisfied and exit from the loop using thebreak
statement.
- Use the
1 2 3 4 5 6 7 8 9 10 11 |
$string = "It is a sample string containing 0123 numbers." $elements = $string -split "\D+" foreach ($element in $elements) { if ($element -match "\d+") { Write-Host "String contains a number." break } } |
1 2 3 |
The string has number(s). |
Here, we used the -split
operator to split the $string
into an array of substrings. The split is based on the specified delimiter, \D+
; it only matches if one or multiple consecutive non-digit characters are found. After the split operation, we will only have substrings consisting of digits, which we saved in $elements
.
Next, we used the foreach
statement to loop over $elements
. Then, for every iteration, we used the if
statement with the -match
operator and \d+
regex to check if it contained the number; this if
statement is the same as we did in the very first example code. Finally, if the if
statement is satisfied, we used Write-Host
to inform the user that the $string
has the number and exit from the loop using the break
statement.
Now, why did we exit from the loop? It is because we are required only to find if the $string
has any number; we are not concerned about how many times we found the occurrence of the number. So, this loop will write to the PowerShell console once, even if there are multiple digits in the string because the break
statement will terminate the loop after the first match is found.
Use Select-String
Cmdlet
Use the Select-String
cmdlet to check if the string contains the number.
1 2 3 4 5 6 7 8 9 10 |
$string = "It is a sample string containing 0123 numbers." $output = Select-String -InputObject $string -Pattern "\d+" if ($output) { Write-Host "The string has number(s)." }else{ Write-Host "The string does not has number(s)." } |
1 2 3 |
The string has number(s). |
First, we defined and initialized the $string
variable to hold a string type value. Next, we used the Select-String
cmdlet with -InputObject
and -Pattern
parameters to check if the input object contains the given pattern.
Now, what are the input objects and patterns? Let’s learn them starting with Select-String cmdlet; it is used to find text in files and strings. This cmdlet supports regular expressions to find a specific pattern in the string or files. Here, the pattern is \d+
, which will only match with numbers, including decimal points, irrespective of the decimal’s position. Input object means the input string or files we specified using the -InputObject
parameter.
The Select-String
cmdlet returned True
if the match was found; otherwise, False
. We used this Boolean value with if
; if it is True
, then run the if
block; otherwise, the else
block.
Further reading:
Now, take a step forward and try a more challenging solution. Assume an array of strings where each element will contain a simple number, a social security number, an email, or it would be just a simple text. Our job is to iterate over each element of the array of strings and check whether it contains a simple number, a social security number, an email, or none of these. We also have to tackle the default case. All this can be done with the following solution. Let’s continue with that.
Use switch
Statement with -Regex
Option
To check if the string has a number or string:
- Use array operator (
@()
) to create an array. - Use the
foreach
loop to iterate over the array created in the previous step. - In every iteration:
- Use the
switch
statement with the-Regex
option to match the case and print the message.
- Use the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$stringArray = @("This string has 123 as id.", "This string has 123-45-6789 as SSN.", "This is just a string") foreach ($string in $stringArray) { switch -Regex ($string){ "\b\d{3}-\d{2}-\d{4}\b" {Write-Host "This string has social security number";Break} "\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b" {Write-Host "This string has an email address";Break} "\b\d+\b" {Write-Host "This string has id number";Break} default {Write-Host "This pattern is something else"} } } |
1 2 3 4 5 6 |
This string has id number This string has social security number This string has an email address This pattern is something else |
First, we used an array operator represented with @()
to create an array having string type values and stored it in the $stringArray
variable. Next, we used the foreach
loop to iterate over $stringArray
and pass each $string
to the switch
statement. Finally, we used the switch
statement with the -Regex
option to work with regular expressions.
For every iteration, the switch
statement matched the case based on the provided regex and displayed a message using the Write-Host
cmdlet. Note that we used the Break
statement to stop the switch
statement as soon as the match was found. The default
case will be executed if no match is found.