Dom*_*nic 5 regex powershell switch-statement
我有一个函数tabLength,应该返回一个字符串.这是为了在文本文档中进行格式化.
任何人都可以检查我的switch语句,看看为什么我在第6行收到错误.这就是switch语句正在经历的"情况".
Function tabLength ( $line ) {
$lineLength = $line.Length
switch -regex ( $lineLength ) {
"[1-4]" { return "`t`t`t" }
"[5-15]" { return "`t`t" }
"[16-24]" { return "`t" }
default { return "`t" }
}
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
Invalid regular expression pattern: [5-15].
At C:\Users\name\desktop\nslookup.ps1:52 char:11
+ "[5-15]" <<<< { return "" }
+ CategoryInfo : InvalidOperation: ([5-15]:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression
Run Code Online (Sandbox Code Playgroud)
它只发生在发送的价值观上[5-15].
[5-15]不是有效的正则表达式字符类.你匹配字符串,而不是数字,所以[5-15]基本上说"匹配'5'到'1'或'5'的单个字符",这不是你想要的.
如果删除该中间条件,则[16-24]应该同样失败.
尝试switch使用不使用正则表达式的语句,但使用脚本块作为条件,以便您可以使用范围进行测试,如下所示:
Function tabLength ( $line ) {
$lineLength = $line.Length
switch ( $lineLength ) {
{ 1..4 -contains $_ } { return "`t`t`t" }
{ 5..15 -contains $_ } { return "`t`t" }
{ 16..24 -contains $_ } { return "`t" }
default { return "`t" }
}
}
Run Code Online (Sandbox Code Playgroud)
在powershell 3+中,您可以使用-in运算符并反转顺序:
Function tabLength ( $line ) {
$lineLength = $line.Length
switch ( $lineLength ) {
{ $_ -in 1..4 } { return "`t`t`t" }
{ $_ -in 5..15 } { return "`t`t" }
{ $_ -in 16..24 } { return "`t" }
default { return "`t" }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |