0

我需要这个正则表达式的帮助。我得到一个如下所示的字符串。我想要类似的东西

服务器名称:AdminServer RUNNING
服务器名称:ServicesServer1 RUNNING

$rv="xxx ServerName: AdminServer  RUNNING  xxxx ServerName: ServicesServer1  RUNNING xxx"
$rv -replace ".*(ServerName: [A-Za-z0-9]*.*[RUNNING|SHUTDOWN])",'$1'
ServerName: ServicesServer1  RUNNING xxx

以我现在所拥有的,我只能得到最后一场比赛?

编辑:

$rv="xxx ServerName: AdminServer  RUNNING  xxxx ServerName: ServicesServer1  RUNNING 
$rv -replace ".*(ServerName: [A-Za-z0-9]*.*RUNNING|SHUTDOWN)",'$1'

ServerName: ServicesServer1  RUNNING xxx

不是

ServerName: AdminServer  RUNNING
ServerName: ServicesServer1  RUNNING

EDIT2:原来我已经过度简化了。字符串看起来更像这样:

$rv='XXX rtification Authority - G3,OU=(c) 2008 GeoTrust Inc. - For authorized use only,O=GeoTrust Inc.,C=US". The loading of the trusted certificate list raised a certificate parsing exception PKIX: Unsupported OID in the AlgorithmIdentifier object: 1.2.840.113549.1.1.11.>
Successfully Connected to Node Manager.
ServerName: SasTTpcAdminServer

RUNNING

Successfully disconnected from Node Manager.
Connecting to Node Manager ...
Successfully Connected to Node Manager.
ServerName: XXXServicesServer1

RUNNING

Successfully disconnected from Node Manager.'
4

3 回答 3

2

试试这个:

 [regex]::Matches($rv, "(ServerName: [A-Za-z0-9]*.*?(?:RUNNING|SHUTDOWN))") | select -expa value

或者

($rv | select-string -Pattern "(ServerName: [A-Za-z0-9]*.*?(?:RUNNING|SHUTDOWN))" -AllMatches ).matches | select -expa value
于 2013-01-15T10:31:06.487 回答
1

虽然这不一定是理想的方法,但在解决一些问题后它会“起作用”:

  1. [RUNNING|SHUTDOWN]是字符类,不是改写。切换到(?:RUNNING|SHUTDOWN)

  2. .*s太贪心了。改为使用.*?

最终的:

$rv -replace ".*?(ServerName: [A-Za-z0-9]*.*?(?:RUNNING|SHUTDOWN))", '$1'

请注意它与最后一位不匹配..但是,可能有更好的解决方案(请注意,这使用了前面讨论的修复和我自己的一些调整):

$r = [regex]::matches($rv,"(ServerName:.*?\w+.*?(?:RUNNING|SHUTDOWN))")
$r[0].Value
# -> ServerName: AdminServer  RUNNING

然后我们可以将捕获组值映射成更简单的东西:

$r | % { $_.Value }
# -> 
# ServerName: AdminServer  RUNNING
# ServerName: ServicesServer1  RUNNING
于 2013-01-15T10:04:40.923 回答
0

试试这个:

$rv -replace '[\s\S]*?(ServerName: \w+)[\s\S]*?((RUNNING|STOPPED).*\n)[\s\S]*?(?(?=ServerName)[\s\S]*?|.*$)', '$1 $2'

对我来说很好。:)

于 2013-01-15T11:28:15.387 回答