如何在PowerShell中的正则表达式中使用条件语句? [英] How to use a conditional statement with regex in PowerShell?
问题描述
大约有十行数据.对于每行数据,我想指出该行是否包含数字.
There are about ten lines of data. For each line of data I want to indicate whether that line contains numerals.
我如何为每一行打印出是的,这行有数字"或否,这行没有数字",准确地打印一次?
How can I print out "yes, this line has numerals" or "no, this line has no numerals" for each and every line, exactly once?
输出:
thufir@dur:~/flwor/csv$
thufir@dur:~/flwor/csv$ pwsh import.ps1
no digits
Name
----
people…
thufir@dur:~/flwor/csv$
代码:
$text = Get-Content -Raw ./people.csv
[array]::Reverse($text)
$tempAttributes = @()
$collectionOfPeople = @()
ForEach ($line in $text) {
if($line -notmatch '.*?[0-9].*?') {
$tempAttributes += $line
Write-Host "matches digits"
}
else {
Write-Host "no digits"
$newPerson = [PSCustomObject]@{
Name = $line
Attributes = $tempAttributes
}
$tempAttributes = @()
$collectionOfPeople += $newPerson
}
}
$collectionOfPeople
数据:
people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10
我打印数字"或无数字"的唯一原因是作为标记,以帮助构建对象.
The only reason I'm printing "digits" or "no digits" is as a marker to aid in building the object.
推荐答案
您可以使用以下内容:
switch -regex -file people.csv {
'\d' { "yes" ; $_ }
default { "no"; $_ }
}
\d
是与数字匹配的正则表达式字符.带-regex
的switch
语句允许将正则表达式用于匹配文本.如果不满足其他条件,则选择default
条件. $_
是当前正在处理的行.
\d
is a regex character matching a digit. A switch
statement with -regex
allows for regex expressions to be used for matching text. The default
condition is picked when no other condition is met. $_
is the current line being processed.
switch
通常比Get-Content
快.由于您确实希望每行执行某些操作,因此您可能不想使用-Raw
参数,因为该参数会将所有文件内容读取为一个字符串.
switch
is generally faster than Get-Content
for line by line processing. Since you do want to perform certain actions per line, you likely don’t want to use the -Raw
parameter because that will read in all file contents as one single string.
# For Reverse Output
$output = switch -regex -file people.csv {
'\d' { "yes" ; $_ }
default { "no"; $_ }
}
$output[($output.GetUpperBound(0))..0)]
这篇关于如何在PowerShell中的正则表达式中使用条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!