[英]Extract value from powershell regex matches
As a part of a buildscript in powershell, I am trying to extract a version number from a string using regular expression. 作为powershell中的buildscript的一部分,我试图使用正则表达式从字符串中提取版本号。 The number is assumed to be in a format xx.yy (eg. 10.6) I need the Integer part (in this example, it would be 10) and the fraction part (example: 6)
假设数字的格式为xx.yy(例如10.6)我需要整数部分(在本例中,它将是10)和分数部分(例如:6)
I want to have a method that checks that both my patterns exists and thereafter extracts the numbers. 我想有一个方法来检查我的模式是否存在,然后提取数字。 (I am very much a novice in powershell, and am trying to avoid using C# functions, but rather powershell itself.)
(我在powershell中非常新手,我试图避免使用C#函数,而是使用PowerShell本身。)
I tried to do this: 我试着这样做:
$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
In doing so, I was hoping that $integralPart and $fractionalPart would contain my numbers, at they match the values they should 在这样做时,我希望$ integralPart和$ fractionalPart包含我的数字,它们匹配它们应该的值
Can anyone explain how this can be done? 任何人都可以解释如何做到这一点?
You need to tell PS that the variables are from global scope with $global
: 你需要告诉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
Output: 输出:
True
True
10
6
Also, you have a typo: inside the GetVersion
, you have $fractionalPart
while the global variable is called $fractionPart
. 此外,你有一个错字:在
GetVersion
,你有$fractionalPart
而全局变量叫$fractionPart
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.