在powershell中从字符串中解析指南

Rom*_*nov 8 regex string powershell

我对 powershell 和 guid 都是新手。网上讨论的所有示例都是为了验证指南。我找不到从字符串中解析 guid 模式的示例。指南的正则表达式是

^{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}$
Run Code Online (Sandbox Code Playgroud)

假设我有一个字符串

"This is a sample string with two guids. Guid1 is {FEB375AB-6EEC-3929-8FAF-188ED81DD8B5}. Guid2 is {B24E0C46-B627-4781-975E-620ED53CD981}"
Run Code Online (Sandbox Code Playgroud)

我想解析这个字符串以获取第一次出现的 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
Run Code Online (Sandbox Code Playgroud)

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

小智 5

我知道我参加这个聚会迟到了,但是 System.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.
Run Code Online (Sandbox Code Playgroud)

不幸的是,这些引用在 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


Mat*_*att 2

有很多方法可以做到这一点。一个简单的方法可以是使用Select-String简化的正则表达式。

$fullString | Select-String -Pattern '{[-0-9A-F]+?}' -AllMatches | Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value
Run Code Online (Sandbox Code Playgroud)

只要它包含十六进制字符和连字符,它就会在大括号之间匹配。不像以前那么具体,但更容易理解。由于我不知道您使用的是哪个版本的 PowerShell,因此可以通过select-string这种方式安全地从结果中获取值。

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

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

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