regex - Powershell-如何根据各种字符和10位数字拆分字符串?

标签 regex powershell

在以下情况下,我需要将字符串分成多个列。我打算将其导出到.csv,这是我的代码的一部分可以工作的地方,我只需要帮助将以下内容分成几列即可。
有时会有名字,有时没有,如果没有,我希望将其留空。请问我该如何编码才能得到结果?
我要做的主要事情之一是10位数字ID,它应该始终是10位数字。
字符串:

  • 20201015 \ smith-1234567890-contract_application-20200418_1889
  • 20201015 \ jones-john-0987654321-salary_contract-20200309_1642

  • 所需结果:
    enter image description here
    代码当前存在问题:
    由于设置了$ Results变量中的拆分方式,因此名称“john”出现在personID列中。我目前在变量中没有名字列,但这就是我要添加的内容。由于10位数字之前有两个破折号,因此我不确定该怎么做。
    #Get the names of the files
    $InStuff = @(Get-ChildItem "\\filepath"-Name -Recurse) 
                                
    #Split out path into columns
    $Results = @(foreach($filepath in $InStuff)
    {
      $parts = $filepath -split '-'; 
      [pscustomobject]@{"DateFirst" = $parts[0]; "PersonID" = $parts[1]; "PersonFileType" = $parts[2]; "FilePath"=$filepath }
    })
    
    谢谢您的帮助。

    最佳答案

    我建议将switch语句与正则表达式模式匹配并最终拆分名称(仅在需要时才发生)组合使用。尽管这只能处理两个名称,但是根据您的描述,这应该可以正常工作。

    $text = @'
    20201015\smith-1234567890-contract_application-20200418_1889
    20201015\jones-john-0987654321-salary_contract-20200309_1642
    '@ -split "`n"
    
    switch -Regex ($text) {
        '^(\d+)\\(.+)-(\d{10})-(.+)-(.+)' {
            $lastname,$firstname = $matches.2 -split '-'
            [pscustomobject]@{
                Date      = $matches.1
                LastName  = $lastname
                FirstName = $firstname
                PersonID  = $matches.3
                FileName  = $matches.4
                DateCode  = $matches.5
            }
        }
    }
    
    输出量
    Date      : 20201015
    LastName  : smith
    FirstName : 
    PersonID  : 1234567890
    FileName  : contract_application
    DateCode  : 20200418_1889
    
    Date      : 20201015
    LastName  : jones
    FirstName : john
    PersonID  : 0987654321
    FileName  : salary_contract
    DateCode  : 20200309_1642
    
    您可以将结果直接传递给Export-Csv-这只是一个示例,我确定您还有其他代码将插入此switch语句。
    $results = switch -Regex ($text) {
        '^(\d+)\\(.+)-(\d{10})-(.+)-(.+)' {
            $lastname,$firstname = $matches.2 -split '-'
            [pscustomobject]@{
                Date      = $matches.1
                LastName  = $lastname
                FirstName = $firstname
                PersonID  = $matches.3
                FileName  = $matches.4
                DateCode  = $matches.5
            }
        }
    }
    
    $results | export-csv c:\temp\exporttest.csv -NoTypeInformation
    

    关于regex - Powershell-如何根据各种字符和10位数字拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64451569/

    相关文章:

    windows - Chef windows_package 守卫存在吗?

    powershell - PowerShell 标准错误输出中的随机换行符

    python - 正则表达式搜索和子

    regex - 什么正则表达式匹配这个模式 : 22-NOV-09

    regex - Powershell重命名文件不起作用 - 没有错误

    azure - 如何使用 powershell 重新启动容器实例

    .net - 用于安装 nuget 包的 PowerShell 脚本

    python - 使用 python 正则表达式提取干净的 URL

    c# - 在字符串中查找多个非连续出现的字符

    windows - 当前两个字符为 ZZ 时删除文件