【问题标题】:How to extract a certain part of a string in powershell如何在powershell中提取字符串的某个部分
【发布时间】:2017-09-15 02:18:22
【问题描述】:

我想从这个字符串中提取“.txt”之前的最后 4 位数字:

09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK

这些代表创建该日志的时间,我想将其显示为 10:58。我从一个文件中读取,该文件有多行类似于显示的行。

Get-Content file.txt | ForEach-Object {
$splitUp = $_ -split "_"
$SC=$splitUp[2] -split "_"
Write-Host $SC
$len = $SC.Length
$folder2 = $SC.Substring($len - 12, 42)
}

我尝试用“_”分隔字符串,然后计算获得的字符串中的字符,并尝试用“子字符串”命令分隔,但收到以下错误。

使用“2”参数调用“子字符串”的异常:“StartIndex 不能 小于零。参数名称:startIndex"

在 line:6 char:5 + $folder2 = $SC.Substring($len - 12, 42)

  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : ArgumentOutOfRangeException

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以使用正则表达式“前瞻”。

    您要搜索的是一组四位数字,后跟“.txt”:

    $string = "09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK"
    $regex = "\d{4}(?=\.txt)"
    [regex]::matches($string, $regex).value
    

    【讨论】:

    • [regex]::match($string, $regex).Value.Insert(2,":") 格式化为 10:58
    • 这是更好的答案。
    • 谢谢!感谢 Mark Wragg,我明白现在发生了什么。
    【解决方案2】:

    可能有一个更优雅的解决方案:

    $String = '09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK'
    
    $String -Match '.*(?=\.txt)' | Out-Null
    $Match = $Matches[0][-4..-1] -Join ''
    
    $Time = [DateTime]::ParseExact($Match, 'HHmm',[CultureInfo]::InvariantCulture)
    $Time.ToShortTimeString()
    
    • 使用 RegEx 获取 .txt 之前的所有字符串
    • 使用数组索引来获取从第 4 个到最后一个字符的字符,并将它们连接在一起作为单个字符串。
    • 使用 ParseExact 将值转换为 DateTime 对象以将其解释为 24 小时时间码
    • 输出该 DateTime 对象的短日期值。

    【讨论】:

    • 非常感谢!我有一个简单的问题。这可能很愚蠢,但我对此很陌生,我真的只是想正确理解它发生了什么。我不明白 '.*(?=\.txt)' 是做什么的。我知道它会在 .txt 之前获取所有字符串,但是如何呢?再次感谢!
    • 根据另一个答案(正则表达式部分更简单/更好,我建议您投票/接受),它正在执行正则表达式“lookahead”,即匹配由表示的模式之前的模式?=。见这里:regular-expressions.info/lookaround.html
    【解决方案3】:

    只需使用 SubstringIndexOf 即可:

    $string="09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK"
    $string.Substring($string.IndexOf('.txt')-4, 4)
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 2016-05-11
      • 2022-11-13
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多