代码之家  ›  专栏  ›  技术社区  ›  Christian Bongiorno

Powershell regex group regex匹配但没有我的组。少了什么?

  •  0
  • Christian Bongiorno  · 技术社区  · 6 年前

    我有一些从jenkins脚本移植的代码,我需要它作为shell命令。所以我知道regex 作品 -让我兴奋的是 比赛 但那就没有我的抓捕小组了。我需要的只是根级目录名:

    foo
    baz
    

    PS E:\SysData\Jenkins\workspace\chb0_chb0mb_example> git diff --name-only origin/master  feature/foo |  %{ Resolve-Path -Relative $_ } | sls  '.\\.*\\.*'  | sls '\\.\\(.+?)\\.*|.*' | %{$_.matches}
    
    
    Groups   : {0}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 0
    Length   : 48
    Value    : .\foo\Nuget\deleteme.txt
    
    Groups   : {0}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 0
    Length   : 55
    Value    : .\baz\QC_OH_DARKESol\deleteme.txt
    
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   mklement0    6 年前

    js2010's helpful answer 指出你的方法的潜在问题( .\\ 应该是 \.\\ GitHub issue | % Line ).

    要更直接地解决问题:

    # Inputs are sample paths.
    '.\foo\Nuget\deleteme.txt',
    '.\bar\QC_OH_DARKESol\deleteme.txt' | 
      foreach { if ($_ -match '^\.\\([^\\]+)') { $Matches[1] } }
    

    上面给出了以下字符串:

    foo
    bar
    

    就是说,它 提取第一个路径组件 遵循文字 .\ 从输入路径,使用 foreach ForEach-Object -match ,和 regular-expression matching operator 到每个输入字符串,其匹配结果将反映在 $Matches 变量,它是 谁的 0 1 包含第一个捕获组的值, 2 第二个。。。; 捕获组(例如。, (?<root>...) ),如果存在,则按其名称列出条目(例如。, root ).


    switch statement 与 -Regex

    switch -Regex (
      git diff --name-only origin/master feature/foo | Resolve-Path -Relative
    ) {
      '^\.\\([^\\]+)' { $Matches[1] } 
    }
    
        2
  •  2
  •   js2010    6 年前

    假设我的问题是对的。一方面,文字句号必须反斜杠。但不管怎样,它都能正常工作。开头没有反斜杠。不是每个人都有git命令。这种模式可能更短,但它是有效的。我正在扩展groups属性,但你没有显示。

    '.\foo\Nuget\deleteme.txt' | sls '.\\(.+?)\\.*|.*' | % matches | % groups
    
    Groups   : {0, 1}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 0
    Length   : 6
    Value    : .\foo\
    
    Success  : True
    Name     : 1
    Captures : {1}
    Index    : 2
    Length   : 3
    Value    : foo
    

    对象 从第一个sls到第二个sls会破坏组捕获。看起来像只虫子。提交: piping select-string to itself and the strange effect on matches

    'abc' | select-string a | select-string '(b)' | % matches | % groups
    
    Groups   : {0}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 0
    Length   : 1
    Value    : a   # should be b
    

    'abc' | select-string a | % line | select-string '(b)' | % matches | % groups
    
    Groups   : {0, 1}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 1
    Length   : 1
    Value    : b
    
    Success  : True
    Name     : 1
    Captures : {1}
    Index    : 1
    Length   : 1
    Value    : b
    
    推荐文章