使用Powershell使用正则表达式从字符串中提取特定数据
我将在powershell中返回以下数据:使用Powershell使用正则表达式从字符串中提取特定数据,powershell,powershell-2.0,Powershell,Powershell 2.0,我将在powershell中返回以下数据: 1)Open;#1 2)Open;#1;#Close;#2;#pending;#6 3)Closed;#5 但我想要这样的输出: 1)1 Open 2) 1 Open 2 Close 6 pending 3) 5 Closed 守则: $lookupitem = $lookupList.Items $CMRSItems = $list.Items | where {$_['ID'] -le 5} $CMRSItems | ForEa
1)Open;#1
2)Open;#1;#Close;#2;#pending;#6
3)Closed;#5
但我想要这样的输出:
1)1 Open
2)
1 Open
2 Close
6 pending
3)
5 Closed
守则:
$lookupitem = $lookupList.Items
$CMRSItems = $list.Items | where {$_['ID'] -le 5}
$CMRSItems | ForEach-Object {
$realval = $_['EventType']
Write-Host "RefNumber: " $_['RefID']
Write-Host $realval
}
感谢您的帮助,因为我的powershell没有那么好。如果没有正则表达式,您可以执行以下操作:
Ignore everything up to the first ')' character
Split the string on the ';' character
foreach pair of the split string
the state is the first part (ignore potentially leading '#')
the number is the second part (ignore leading '#')
或者您可以使用.NETSystem.Text.RegularExpressions.Regex
类和以下正则表达式执行此操作:
(?:#?(?<state>[a-zA-Z]+);#(?<number>\d);?)
(?:#?(?[a-zA-Z]+)#(?\d);)
Matches
方法返回的MatchCollection
上的捕获属性将是一个集合,其中每个项将包含组中的两个实例
集合;分别命名为state
和number
。能否显示给出此输出的代码。修改此代码可能比编写更多代码来更改输出更容易。谢谢JPBlank编辑代码谢谢Robert的提示。但powershell不太好:(另外,我要处理的字符串是“Open;#1;#Close;#2;#pending;#6”。这也是一个动态字符串,不是硬编码的。字符串的格式,例如State1;#Num1;#State2;#Num2
是固定的(如果不是固定的,则在没有学习算法的情况下,您将很难解析它)以上两种建议的解决方案都适用于动态字符串。我可能会建议使用正则表达式解决方案。请阅读PowerShell中的.NET类的使用,并阅读System.Text.RegularExpressions.Regex
文档。如果您在尝试后遇到困难,请提出一个关于如果你被卡住了,请在这里添加一个新问题的链接,作为对这个答案的评论。