为什么这个 switch 语句不匹配子字符串?

gab*_*l__ 1 powershell switch-statement

我试图将字符串变量的子字符串与 switch 语句匹配:

#$value = "55"
#$value = "55-"
#$value = "55+"
$value = "+55"

switch ($Value) {
    "^\+" {"Starts With +"}
    "^\d" {"Starts With a digit"}

    "+$" {"Ends with +"}
    "-$" {"Ends with -"}
}

Run Code Online (Sandbox Code Playgroud)

switch 语句不会触发。即使我这样做了"^\+.*" {"Starts With +"}。我确实需要部分匹配$Value. 我究竟做错了什么?

von*_*ryz 7

发生这种情况是因为默认情况下switch 不需要正则表达式。要使用正则表达式进行匹配,请传递-regexfor 语句。就像这样,

 $value = "+55"
 switch -regex ($Value) {
     "^\+" {"Starts With +"}
     "^\d" {"Starts With a digit"}     
     "\+$" {"Ends with +"} #Remember to escape quantifier
     "-$" {"Ends with -"}
     default {"no match"}
 }
# Output
Starts With +
Run Code Online (Sandbox Code Playgroud)