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
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.+
注:
-match
,PowerShell 的正则表达式匹配运算符,最多只能找到 一个 匹配;需要借助 .NET API 进行“多个”匹配,这会带来极大的复杂性; GitHub 问题 #7867 建议引入一个 -matchall
运算符来解决这个问题 - 虽然该提案已获得批准,但尚未有人加紧实施。
:
-split "-"
:
对-
(因为它们充当分隔符),这使得过滤相关标记变得更加困难 不将标记限制为仅前两行。
的解决方案,是,但需要额外使用
-match
,这使得解决方案更加复杂且效率较低:
# Same output as above.
$string -split '(?m)(^- .+\n.+\n.+)' -match '^- '
将正则表达式的相关部分包含在
(...)
中,即使其成为
捕获组,导致
-split
在返回的标记中包含该组的匹配项;
-match '^- '
然后过滤掉所有以 -
开头的 not 标记,只留下感兴趣的 2 个两行字符串。