0
votes

Comment obtenir un nombre décimal d'une chaîne dans PowerShell?

  1. J'ai une chaîne contenant une valeur décimale (par exemple «good1432.28morning to you» )
  2. J'ai besoin d'extraire 1432.28 de la chaîne et de le convertir en décimal

0 commentaires

3 Réponses :


2
votes

Cela peut être fait de nombreuses manières, impossible de trouver une question / solution exactement similaire dans stackoverflow, voici donc une solution rapide qui a fonctionné pour moi .

1432.28

Appel de la fonction

$x = get-Decimal-From-String 'good1432.28morning to you'

Résultat

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

}


2 commentaires

Je recommanderais une approche positive (plutôt que de supprimer tout ce qui n'est pas numérique, sélectionnez tout ce qui est numérique) d'une vue sémantique et de performance: if ('good1432.28morning to you' -Match '[\d\.\d]+') { $Matches.Values }


le positif est toujours meilleur :-)



0
votes

Autre solution:

-join ('good143.28morning to you' -split '' | where {$_ -ge '0' -and $_ -le '9' -or $_ -eq '.'})


0 commentaires

0
votes

Une autre alternative:

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

Détails Regex

function Get-Decimal-From-String {
    # Function receives string containing decimal
    param([String]$myString)

    if ($myString -match '(\d+(?:\.\d+)?)') { [decimal]$matches[1] } else { [decimal]::Zero }
}


0 commentaires