[英]Parse guids out of a string in 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
想知道表達方式或我調用它的方式是否有問題。
我知道我遲到了,但是 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($_) }
有很多方法可以做到這一點。 一個簡單的方法是使用帶有簡化正則表達式的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]+?)}')
我的方式:
$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] 將擁有第一個 guid。
我個人認為正則表達式很棒,但是如果我發現如果我可以讓系統完成這項工作,那么我會選擇該解決方案。
所以對於 GUID,我會做一些類似的事情:
If([System.Guid]::Parse($Majic_GUID_String_To_Test) -is [Guid] ) { Then continue programming ... }
所以我希望對你們中的一些人有所幫助,Porky
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.