【发布时间】:2020-02-16 09:56:05
【问题描述】:
大约有十行数据。对于每一行数据,我想指出该行是否包含数字。
我怎样才能为每一行打印出“是的,这一行有数字”或“不,这一行没有数字”,只打印一次?
输出:
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
我打印“数字”或“无数字”的唯一原因是作为帮助构建对象的标记。
【问题讨论】:
-
每次文本匹配
^[^0-9]+$,你打印No Digits怎么样 -
目前,每次出现与
[0-9]不匹配的内容时,您的代码都会打印 No Digits。你看到问题了吗?每次遇到一个字母,就会打印No Digits。 -
目前,你的代码告诉正则表达式匹配任何不是
[0-9]的东西,由你的代码$line -notmatch '[0-9]'给出。试着从计算机的角度来考虑,没有常识。 “J”不是数字。 'o' 不是数字。 'e' 不是数字。所以当它遇到 'Joe' 时,它会打印 3 次“No digits”。 -
请改用此代码,
if($line -notmatch '.*?[0-9].*?') -
我对 powershell 的了解为零,我试图用我的正则表达式经验来回答这个问题。很可能是 - $text 中的 $line 可能会给你整个文件而不是一行
标签: regex powershell if-statement syntax iteration