用“-”分割字符串

问题描述 投票:0回答:1
System.Management.Automation.RemoteException
name: CLD:HYB_Z_BASIS_ADMIN_SUPER
description: Basis Administrator
readOnly: 
roleReferences:
- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_Administrator
  name: AuthGroup_Administrator
- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_BusinessExpert
  name: AuthGroup_BusinessExpert
OK

我有上面的字符串,每行由 CRLF 分隔。我正在尝试提取以下信息并将其拆分为用“-”分隔的两行,这样我可以获得两行数组,但我没有得到正确的结果。

我的代码是:

$Myarray = $string -split "-"

- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_Administrator
  name: AuthGroup_Administrator
- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_BusinessExpert
  name: AuthGroup_BusinessExpert
powershell split
1个回答
1
投票

使用

System.Text.RegularExpressions.Regex.Matches()
方法从字符串中提取 多个 匹配项:

$string = @'
System.Management.Automation.RemoteException
name: CLD:HYB_Z_BASIS_ADMIN_SUPER
description: Basis Administrator
readOnly: 
roleReferences:
- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_Administrator
  name: AuthGroup_Administrator
- roleTemplateAppId: it!b2455
  roleTemplateName: AuthGroup_BusinessExpert
  name: AuthGroup_BusinessExpert
OK
'@

# Find all matches for the given regex and return the matched
# text (.Value) for each.
# Returns 2 three-line strings.
[regex]::Matches($string, '(?m)^- .+\n.+\n.+').Value

注意:该解决方案依赖于单多行字符串作为输入。如果你有一个 array 字符串,请先用

[Environment]::NewLine
将它们连接起来;例如
$multilineString = 'foo', 'bar' -join [Environment]::NewLine
;您还可以应用此技术来从外部程序捕获的输出 - 请参阅此答案的底部部分。

有关正则表达式 (?m)^- .+\n.+

 的详细 解释以及对其进行实验的能力,请参阅 此 regex101.com 页面

注:

  • 从 PowerShell 7.3.x 开始,
    -match
    ,PowerShell 的正则表达式匹配运算符,最多只能找到 一个 匹配;需要借助 .NET API 进行“多个”匹配,这会带来极大的复杂性; GitHub 问题 #7867 建议引入一个 -matchall 运算符来解决这个问题 - 虽然该提案已获得批准,但尚未有人加紧实施。
    
    
至于
你尝试过的

-split "-"


    整个
  • 字符串进行标记,因此您将获得需要后过滤的不相关信息
  • 从结果标记中排除
  • -(因为它们充当
    分隔符
    ),这使得过滤相关标记变得更加困难 不将标记限制为仅前两行。
  • 使用

-split

的解决方案,
,但需要额外使用-match
,这使得解决方案更加复杂且效率较低:
# Same output as above. $string -split '(?m)(^- .+\n.+\n.+)' -match '^- '

将正则表达式的相关部分包含在
(...)

中,即使其成为

捕获组
,导致-split在返回的标记中
包含
该组的匹配项; -match '^- ' 然后过滤掉所有以
- 
开头的 not 标记,只留下感兴趣的 2 个两行字符串。
    

© www.soinside.com 2019 - 2024. All rights reserved.