PowerShell: How to Extract Only Numbers from String


You can use the following method in PowerShell to extract numbers from a string:

Method 1: Extract Only Numbers from String

$numbers_only = $my_string -replace "[^0-9]" , ''

Method 2: Extract Only Numbers and Decimal Point from String

$numbers_decimals = if ($my_string -Match '[\d\.\d]+') {$Matches.Values}

The following examples show how to use each method in practice.

Example 1: Extract Only Numbers from String in PowerShell

Suppose that we have the following string that contains both numbers and letters:

  • Dallas00549Mavericks

And suppose that we would like to extract only the numbers from the string to get the following output:

  • 00549

We can use the following syntax to do so:

$my_string = "Dallas00549Mavericks"
$numbers_only = $my_string -replace "[^0-9]" , ''

The following screenshot shows how to use this syntax in practice:

PowerShell extract numbers from string

Notice that this returns 00549, which represents only the numbers in the string.

Note: This method works by using the –replace operator to replace every character that is not a number with nothing. This leaves us with only numbers.

Example 2: Extract Only Numbers and Decimal Point from String in PowerShell

Suppose that we have the following string that contains numbers, a decimal point, and letters:

  • Dallas549.37Mavericks

And suppose that we would like to extract only the numbers and the decimal point from the string to get the following output:

  • 549.37

We can use the following syntax to do so:

$my_string = "Dallas549.37Mavericks"
$numbers_decimals = if ($my_string -Match '[\d\.\d]+') {$Matches.Values}

The following screenshot shows how to use this syntax in practice:

PowerShell extract numbers and decimal point from string

Notice that this returns 549.37, which represents only the numbers and the decimal point in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply