#string #powershell #get #decimal #extract
#строка #powershell #получить #десятичное #извлечь
Вопрос:
- У меня есть строка, содержащая десятичное значение (например, «good1432.28morning to you»)
- Мне нужно извлечь 1432.28 из строки и преобразовать его в десятичное число
Ответ №1:
Это можно сделать разными способами, не удалось найти точный аналогичный вопрос / решение в 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
}
Вызов функции
$x = get-Decimal-From-String 'good1432.28morning to you'
Результат
1432.28
Комментарии:
1. Я бы рекомендовал подход positief (вместо удаления всего, что не является числовым, выберите все, что числовое) из семантического представления и представления производительности:
if ('good1432.28morning to you' -Match '[d.d] ') { $Matches.Values }
2. положительный всегда лучше 🙂
Ответ №2:
Другое решение :
-join ('good143.28morning to you' -split '' | where {$_ -ge '0' -and $_ -le '9' -or $_ -eq '.'})
Ответ №3:
Другой вариант:
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)
)