I want to check if a string contains a numeric value. I have this code :
$string = "some string that contains 123456 in the middle"
$substring = $string.substring(27,9).Trim()
I have $substring which will be containing "123456" and I found this IsNumeric function here : In PowerShell, how can I test if a variable holds a numeric value?
The thing is that this when I'm extracting it from $string it acts like string type and IsNumeric returns false since it's comparing it to the all numeric types. and even tough it will contain a number the output of IsNumeric will be false.
Is there a better way to check if string contains numeric values?
You can use a regular expression match to test it:
if($substring -match "^\d+$")
{
# Do something
}
This should work for any string which contains only digits (i.e. is a positive integer). Change the pattern to ^-?\d+$
if you want to include negative integers.