[英]How to get decimal number out of string in powershell?
This can be done in many ways, could not find exact similar question / solution in stackoverflow, so here is a quick solution that worked for me .这可以通过多种方式完成,在 stackoverflow 中找不到完全相似的问题/解决方案,所以这里有一个对我有用的快速解决方案。
Function get-Decimal-From-String
{
# Function receives string containing decimal
param([String]$myString)
# Will keep only decimal - can be extended / modified for special needs
$myString = $myString -replace "[^\d*\.?\d*$/]" , ''
# Convert to Decimal
[Decimal]$myString
}
Calling the Function拨打电话 Function
$x = get-Decimal-From-String 'good1432.28morning to you'
Result结果
1432.28
Other solution:其他解决方案:
-join ('good143.28morning to you' -split '' | where {$_ -ge '0' -and $_ -le '9' -or $_ -eq '.'})
Another alternative:另一种选择:
function Get-Decimal-From-String {
# Function receives string containing decimal
param([String]$myString)
if ($myString -match '(\d+(?:\.\d+)?)') { [decimal]$matches[1] } else { [decimal]::Zero }
}
Regex details正则表达式详细信息
( Match the regular expression below and capture its match into backreference number 1
\d Match a single digit 0..9
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?: Match the regular expression below
\. Match the character “.” literally
\d Match a single digit 0..9
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)? Between zero and one times, as many times as possible, giving back as needed (greedy)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.