[英]Extract the number before a file extension (.ps1) in a string
创建文件的 cmdlet 返回一个文本块,其中是文件的名称。 该文件的格式为 string[number].ps1,但数字是随机的,因此我想提取该数字并将其存储在变量中。
供参考的文本块:
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:20 char:8\n+ using Microsoft.Build.Framework;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:20 char:3\n+ using Microsoft.Build.Framework;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:21 char:8\n+ using Microsoft.Build.Utilities;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:21 char:3\n+ using Microsoft.Build.Utilities;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
我认为$result -match '\\d\\d+(?=\\.\\w+)'
会起作用,但它只返回找到数字的行,而不仅仅是数字。
使用集合(而不是单个值)作为 LHS, -match
运算符:
充当过滤器- 即返回匹配元素的子数组而不是布尔值
不填充自动$Matches
变量与匹配运营商的结果。
这就是为什么你的输出包括匹配的行作为一个整体。
只返回匹配的部分,你可以使用一个switch
语句与-Regex
选项循环在你的线阵列,在这种情况下, $Matches
填充每个输入线:
# Array of sample lines.
# For illustrative purposes I've tweaked the `script<number>.ps1`
# tokens to have successive numbers.
$lines = @'
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:20 char:8\n+ using Microsoft.Build.Framework;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script36.ps1:20 char:3\n+ using Microsoft.Build.Framework;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script37.ps1:21 char:8\n+ using Microsoft.Build.Utilities;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script38.ps1:21 char:3\n+ using Microsoft.Build.Utilities;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
'@ -split '\r?\n'
# Perform the matching, line by line,
# and output each line's matching part,
# resulting in an array of strings.
# Prepend
# $result =
# to store the array in a variable.
switch -Regex ($lines) {
'\d+(?=\.\w+)' { $Matches[0] } # to extract only the *1st* match,
# append `; break` inside the { ... }
}
以上产生:
35
36
37
38
请注意, switch
还支持使用-File
选项直接从文件中读取行
( switch -Regex -File $filePath { ... }
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.