在Tcl中,switch
语句非常强大,可以处理字符串匹配和模式匹配。我们将详细说明如何使用字符串匹配以及三种模式匹配(-exact
,-glob
,-regexp
),并举多个例子进行说明。
字符串匹配
示例 1:基本字符串匹配
#!/usr/bin/env tclsh
set user_input "hello"
switch $user_input {
"hello" {
puts "User said hello."
}
"goodbye" {
puts "User said goodbye."
}
default {
puts "Unknown input."
}
}
示例 2:处理多种字符串
#!/usr/bin/env tclsh
set command "start"
switch $command {
"start" {
puts "Starting the process."
}
"stop" {
puts "Stopping the process."
}
"pause" {
puts "Pausing the process."
}
default {
puts "Unknown command."
}
}
模式匹配
-exact 模式匹配
-exact
是默认模式,表示精确匹配。
示例 1:基本精确匹配
#!/usr/bin/env tclsh
set mode "active"
switch -exact $mode {
"active" {
puts "The system is active."
}
"inactive" {
puts "The system is inactive."
}
default {
puts "Unknown mode."
}
}
示例 2:处理精确匹配
#!/usr/bin/env tclsh
set level "admin"
switch -exact $level {
"admin" {
puts "Administrator access granted."
}
"user" {
puts "User access granted."
}
"guest" {
puts "Guest access granted."
}
default {
puts "Access level unknown."
}
}
-glob 模式匹配
-glob
允许使用通配符进行模式匹配。
示例 1:处理文件扩展名
#!/usr/bin/env tclsh
set filename "report.pdf"
switch -glob $filename {
"*.txt" {
puts "This is a text file."
}
"*.pdf" {
puts "This is a PDF file."
}
"*.doc" - "*.docx" {
puts "This is a Word document."
}
default {
puts "Unknown file type."
}
}
示例 2:处理不同模式输入
#!/usr/bin/env tclsh
set input "error-404"
switch -glob $input {
"error-*" {
puts "An error occurred."
}
"warning-*" {
puts "A warning is issued."
}
"info-*" {
puts "Informational message."
}
default {
puts "Unknown message type."
}
}
-regexp 模式匹配
-regexp
允许使用正则表达式进行模式匹配。
示例 1:处理正则表达式匹配
#!/usr/bin/env tclsh
set text "Hello123"
switch -regexp $text {
{^Hello} {
puts "Text starts with 'Hello'."
}
{\d+$} {
puts "Text ends with digits."
}
default {
puts "No match found."
}
}
示例 2:复杂正则表达式匹配
#!/usr/bin/env tclsh
set string "user@example.com"
switch -regexp $string {
{^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$} {
puts "Valid email address."
}
default {
puts "Invalid email address."
}
}
详细解释
字符串匹配
- 基本字符串匹配:直接对比输入字符串和预定义的字符串,只有完全匹配时才执行相应的代码块。
- 处理多种字符串:可以根据不同的命令执行不同的操作,通过
default
处理未知命令。
-exact 模式匹配
- 基本精确匹配:与字符串匹配类似,但明确使用
-exact
选项表示精确匹配。 - 处理精确匹配:根据不同的精确匹配条件执行相应操作。
-glob 模式匹配
- 处理文件扩展名:使用通配符匹配文件扩展名,
*.txt
匹配所有以.txt
结尾的文件。 - 处理不同模式输入:使用通配符匹配不同模式的输入,如
error-*
匹配所有以error-
开头的字符串。
-regexp 模式匹配
- 处理正则表达式匹配:使用正则表达式匹配字符串,
^Hello
匹配所有以Hello
开头的字符串。 - 复杂正则表达式匹配:使用更复杂的正则表达式匹配,如验证邮箱地址的格式。