Powershell 正则表达式 select 变量中的字符串
powershell regex select string in variable
我正在尝试创建一个脚本,select 公司计算机主机名中的四个数字。
我已经在一个正则表达式网站上测试了正则表达式 '\d{4}'
,它对 select 这四个数字工作正常。但是当它与 powershell 一起使用时,y 只会得到 $true 或 $false。
我需要将这 4 个数字保存在一个变量中以备后用,但我还没有实现。
有什么想法吗??
$machinename = "mac0016w701"
$test = $machinename -match '\d{4}'
$test2= Select-String -Pattern '\d{4}' -inputobject $machinename
$test2
-match
是 returns true/false 的运算符,因此您可以在测试中使用它。如果你想要来自正则表达式的值,它会设置魔法变量 $Matches
,例如
PS D:\> 'computer1234' -match '\d{4}'
True
PS D:\> $matches[0]
1234
或者,您可以使用:
[regex]::Matches('computer1234', '\d{4}').Value
我正在尝试创建一个脚本,select 公司计算机主机名中的四个数字。
我已经在一个正则表达式网站上测试了正则表达式 '\d{4}'
,它对 select 这四个数字工作正常。但是当它与 powershell 一起使用时,y 只会得到 $true 或 $false。
我需要将这 4 个数字保存在一个变量中以备后用,但我还没有实现。
有什么想法吗??
$machinename = "mac0016w701"
$test = $machinename -match '\d{4}'
$test2= Select-String -Pattern '\d{4}' -inputobject $machinename
$test2
-match
是 returns true/false 的运算符,因此您可以在测试中使用它。如果你想要来自正则表达式的值,它会设置魔法变量 $Matches
,例如
PS D:\> 'computer1234' -match '\d{4}'
True
PS D:\> $matches[0]
1234
或者,您可以使用:
[regex]::Matches('computer1234', '\d{4}').Value