【问题标题】:Powershell: Convert string with/without leading numbers to integerPowershell:将带/不带前导数字的字符串转换为整数
【发布时间】:2021-04-28 15:48:18
【问题描述】:

我正在寻找将带有前导数字的字符串转换为整数值的最聪明的方法。它应该只使用文本字符串前面的前导数字,如果没有前导数字,则应使用 0。 目前我正在使用这个code-sn-p,但我希望有更好的方法:

[int][regex]::Match('123test456','^\d*').value

【问题讨论】:

  • Regex 非常适合这类主题
  • 就个人而言,我会使用-replace —> [int]('123hih456' -replace '\D.*')
  • @AdminOfThings 我认为这是最短且最快的解决方案。

标签: string powershell integer


【解决方案1】:

或者这个。如果找到匹配项,自动 $matches 哈希表变量会给出答案。

if ('123test456' -match '^\d*') { $matches[0] }

123

【讨论】:

  • @zett42 好点。我改为使用 if 语句。
  • 如果字符串没有前导数字,则需要 [int] 对话来处理这种情况。
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2020-04-15
  • 2020-05-25
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多