【问题标题】:How to get decimal number out of string in powershell?如何在powershell中从字符串中获取十进制数?
【发布时间】:2021-02-26 17:56:28
【问题描述】:
  1. 我有一个包含十进制值的字符串(例如 'good1432.28morning 给你的
  2. 我需要从字符串中提取 1432.28 并将其转换为十进制

【问题讨论】:

    标签: string powershell get decimal extract


    【解决方案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
    

    【讨论】:

    • 我会推荐一种 positief 方法(而不是删除所有 数字,选择所有 数字) 从语义和性能的角度来看:if ('good1432.28morning to you' -Match '[\d\.\d]+') { $Matches.Values }
    • 积极的总是更好:-)
    【解决方案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)
      )
      

      【讨论】:

        【解决方案4】:
        ("good1432.28morning to you" -split "\.")[1]
        

        (1557.18 -split "\.")[1]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-18
          • 2022-01-16
          • 2021-12-01
          • 2012-05-04
          相关资源
          最近更新 更多