在 PowerShell 中检查字符串是否包含数值? [英] Check if string contains numeric value in PowerShell?

查看:546
本文介绍了在 PowerShell 中检查字符串是否包含数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个字符串是否包含一个数值.我有这个代码:

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()

我有 $substring 它将包含123456",我在这里找到了这个 IsNumeric 函数:在 PowerShell 中,我怎样才能测试变量是否包含数值?

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?

问题是,当我从 $string 中提取它时,它的行为类似于字符串类型,而 IsNumeric 返回 false,因为它将它与所有数字类型进行比较.即使很难,它也会包含一个数字,IsNumeric 的输出将是假的.

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
}

这应该适用于任何只包含数字的字符串(即正整数).如果要包含负整数,请将模式更改为 ^-?\d+$.

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.

这篇关于在 PowerShell 中检查字符串是否包含数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆