在powershell中解析一个字符串中的guid

时间:2015-09-30 18:15:37

标签: regex string powershell

我是powershell和guids的新手。网上讨论的所有例子都用于验证guid。我找不到用字符串解析guid模式的例子。 guid的正则表达式是

^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$

说我有一个带

的字符串
"This is a sample string with two guids. Guid1 is {FEB375AB-6EEC-3929-8FAF-188ED81DD8B5}. Guid2 is {B24E0C46-B627-4781-975E-620ED53CD981}"

我想解析这个字符串以获得第一次出现的guid,即{FEB375AB-6EEC-3929-8FAF-188ED81DD8B5}。我怎样才能在PowerShell中做到这一点。

我尝试了以下内容。但它不起作用:

$fullString = "This is a sample string with two guids. Guid1 is {FEB375AB-6EEC-3929-8FAF-188ED81DD8B5}. Guid2 is {B24E0C46-B627-4781-975E-620ED53CD981}"

$guid = [regex]::match($fullString, '^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$')
Write-Host $guid.Groups[1].Value

想知道表达式或我调用它的方式是否有问题。

4 个答案:

答案 0 :(得分:1)

我的方式:

$string = "This is a sample string with two guids. Guid1 is {FEB375AB-6EEC-3929-8FAF-188ED81DD8B5}. Guid2 is {B24E0C46-B627-4781-975E-620ED53CD981}" 
$string -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}'

然后$ matches [0]将具有第一个引导。

答案 1 :(得分:0)

许多方法都可以做到这一点。一个简单的可能是Select-String与简化的正则表达式。

$fullString | Select-String -Pattern '{[-0-9A-F]+?}' -AllMatches | Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value

只要它包含十六进制字符和连字符,这将匹配花括号。不像以前那样具体,但更容易理解。由于我不知道您使用的是什么版本的PowerShell,因此可以通过这种方式安全地完成select-string结果中的值。

最初我只是被正则表达式长度所蒙蔽,并没有注意到PetSerAl指出的是什么。您的正则表达式中的字符串和字符串锚点的开头与测试字符串不匹配,更不用说多个值了。

即使删除那些,您只能从$guid获得一个结果。要获得多个结果,您需要使用不同的方法。

[regex]::Matches($fullString,'{([-0-9A-F]+?)}')

答案 2 :(得分:0)

我知道我参加这个聚会很晚,但是System.Guid类提供了自己的解析器。它很容易使用。它还说明了各种公认的GUID格式。

$Result = [System.Guid]::empty #Reference for the output, required by the method but not useful in powershell
[System.Guid]::TryParse("foo",[System.Management.Automation.PSReference]$Result) # Returns true if successfully parsed and assigns the parsed guid to $Result, otherwise false.

$Result = [System.Guid]::empty #Reference for the output, required by the method but not useful in powershell
[System.Guid]::TryParse("12345678-1234-1234-1234-987654321abc",[System.Management.Automation.PSReference]$Result) # Returns true if successfully parsed, otherwise false.

不幸的是,这些引用在powershell中不能很好地工作,因此您需要在实际解析guid时遵循它。

$string = "12345678-1234-1234-1234-987654321abc"
$Result = [System.Guid]::empty
If ([System.Guid]::TryParse($string,[System.Management.Automation.PSReference]$Result)) {
$Result = [System.Guid]::Parse($string)
} Else {
$Result = $null
}

或者您可以仅使用try / catch来查看其是否解析。

$string = "12345678-1234-1234-1234-987654321abc"
Try { $Result = [System.Guid]::Parse($string) } Catch { $Result =  $Null } Finally { $Result }

要演示其可以使用的所有格式,可以执行以下操作:

$guid = [guid]"12345678-1234-1234-1234-987654321abc"
"d","n","p","b","x" | ForEach-Object { $guid.tostring($_) }

答案 3 :(得分:0)

我个人认为正则表达式很棒,但是如果我发现如果我可以让系统完成这项工作,那么我会选择该解决方案。

所以对于 GUID,我会做一些类似的事情:

If([System.Guid]::Parse($Majic_GUID_String_To_Test) -is [Guid] ) { Then continue programming ... }

所以我希望对你们中的一些人有所帮助, 猪肉