[英]How to get decimal number out of string in powershell?
這可以通過多種方式完成,在 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
}
撥打電話 Function
$x = get-Decimal-From-String 'good1432.28morning to you'
結果
1432.28
其他解決方案:
-join ('good143.28morning to you' -split '' | where {$_ -ge '0' -and $_ -le '9' -or $_ -eq '.'})
另一種選擇:
function Get-Decimal-From-String {
# Function receives string containing decimal
param([String]$myString)
if ($myString -match '(\d+(?:\.\d+)?)') { [decimal]$matches[1] } else { [decimal]::Zero }
}
正則表達式詳細信息
( 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.