Check if String Contains Number in PowerShell

Check if String contains Number in PowerShell

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.

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 means 01.23, .0123, and 0123. 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.

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 the if condition is satisfied and exit from the loop using the break statement.

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.

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.

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 -RegexOption

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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *