我正在尝试将字符串变量的子字符串与 switch 语句匹配:
#$value = "55"
#$value = "55-"
#$value = "55+"
$value = "+55"
switch ($Value) {
"^\+" {"Starts With +"}
"^\d" {"Starts With a digit"}
"+$" {"Ends with +"}
"-$" {"Ends with -"}
}
switch 语句不会触发。即使我这样做
"^\+.*" {"Starts With +"}
。我真的需要部分匹配$Value
的内容。我做错了什么?
发生这种情况是因为
switch
不期望默认有正则表达式。要使用正则表达式进行匹配,请为语句传递 -regex
。就像这样,
$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 +