如何忽略字母/单词? [英] How to ignore letters/words?
问题描述
假设我有以下代码:
$size = 23.9
$size = "$size GB"
write $size
我想在其他事情上使用相同的变量,即
i want to use the same variable for other things, i.e.
if ($size -lt 20)
{...}
这显然是一个问题,因为 $size
这里有 GB/is a string
this will obviously be an issue because $size
here has GB/is a string
如何忽略字符串部分?
我正在寻找这样的东西:
i am looking for something like this:
if($($size -replace ("anything after the numbers", "")) -lt 20)
{....}
推荐答案
如果您坚持使用字符串并保持使用 -replace
运算符,您可以使用以下方法:
If you insist on working with a string and keeping with the -replace
operator, you can use the following:
[double]($size -replace "[^\d\.]+$")
如果您维护一个数值类型,例如 int
或 double
,您可以使用其他方法来处理您的数据.你仍然可以输出一个字符串,同时保持 $size
为双精度.
If you maintain a numeric value type like int
or double
, you can use other means to work with your data. You can still output a string while keeping $size
a double.
$size = 23.9
$unit = 'GB'
"{0} {1}" -f $size,$unit
23.9 GB
与上述示例非常相似的概念是将 $size
创建为自定义对象.
A very similar concept as the above example would be to create $size
as a custom object.
$size = [pscustomobject]@{Size = 23.9; Unit = 'GB'}
"{0} {1}" -f $size.Size,$size.Unit
您可以进行动态单元分配.如果我们假设您从字节大小开始,您可以分配单位并进行转换.
You can do dynamic unit assignment. If we assume you are starting with a size in bytes, you can assign the unit and do the conversion.
if ($size -ge 1GB)
{
$newSize = [pscustomobject]@{
Size = $size/1GB; Unit = 'GB'
}
}
elseif ($size -ge 1MB)
{
$newSize = [pscustomobject]@{
Size = $size/1MB; Unit = 'MB'
}
}
elseif ($size -ge 1KB)
{
$newSize = [pscustomobject]@{
Size = $size/1KB; Unit = 'KB'
}
}
else
{
$newSize = [pscustomobject]@{
Size = $size; Unit = 'B'
}
}
这篇关于如何忽略字母/单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!