[英]Extract value from powershell regex matches
作為powershell中的buildscript的一部分,我試圖使用正則表達式從字符串中提取版本號。 假設數字的格式為xx.yy(例如10.6)我需要整數部分(在本例中,它將是10)和分數部分(例如:6)
我想有一個方法來檢查我的模式是否存在,然后提取數字。 (我在powershell中非常新手,我試圖避免使用C#函數,而是使用PowerShell本身。)
我試着這樣做:
$integralPart="A"
$fractionPart="B"
function GetVersion {
param([string]$strVersion)
$integralPattern="^[0-9]+(?=\.)"
$fractionalPattern="(?<=\.)[0-9]+$"
#Check if string consists of an integral and fractional part
If ($strVersion -match $integralPattern -eq $True -and $strVersion -match $fractionalPattern -eq $True)
{
$strVersion -match $integralPattern
$integralPart = $matches[0]
$strVersion -match $fractionalPattern
$fractionalPart = $matches[0]
}
else
{
Write-Host "You did not enter a double with an integer and a fractional part (eg. 10.6)"
Exit
}
}
GetVersion (Read-Host 'Enter program version')
Write-Host $integralPart
Write-Host $fractionPart
在這樣做時,我希望$ integralPart和$ fractionalPart包含我的數字,它們匹配它們應該的值
任何人都可以解釋如何做到這一點?
你需要告訴PS這些變量是來自全球范圍的$global
:
$integralPart="A"
$fractionPart="B"
function GetVersion {
param([string]$strVersion)
$integralPattern="^[0-9]+(?=\.)"
$fractionalPattern="(?<=\.)[0-9]+$"
#Check if string consists of an integral and fractional part
If ($strVersion -match $integralPattern -eq $True -and $strVersion -match $fractionalPattern -eq $True)
{
$strVersion -match $integralPattern
$global:integralPart = $matches[0] // SEE HERE
$strVersion -match $fractionalPattern
$global:fractionPart = $matches[0] // SEE HERE
}
else
{
Write-Host "You did not enter a double with an integer and a fractional part (eg. 10.6)"
Exit
}
}
GetVersion "10.6"
Write-Host $integralPart
Write-Host $fractionPart
輸出:
True
True
10
6
此外,你有一個錯字:在GetVersion
,你有$fractionalPart
而全局變量叫$fractionPart
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.