" regexp"命令用于匹配Tcl中的正则表达式。它由多个规则组成,下表解释了这些规则及其相应的用法。
Sr.No. | Rule & Remark |
---|---|
1 | x 完全符合。 |
2 | [a-z] a-z中的任何小写字母。 |
3 | . 任何字符。 |
4 | ^ 匹配开头字符串。 |
5 | $ 匹配结束字符串。 |
6 | \^ 反斜线 匹配特殊字符^。 |
7 | () 将以上序列添加到括号内以创建正则表达式。 |
8 | x* 匹配x的0次或多次。 |
9 | x+ 匹配x的1个或更多。 |
10 | [a-z]? 匹配x的0或1次。 |
11 | {digit} 匹配精确数字,包含0-9的数字。 |
12 | {digit,} 匹配至少3个或更多数字出现,包含0-9的数字。 |
13 | {digit1,digit2} 匹配digit1和digit2出现次数之间的范围匹配。 |
正则表达式的语法如下-
regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn
Submatch1到SubMatchn是可选的subMatch变量,用于保存子匹配模式的输出。
#!/usr/bin/tclsh regexp {([A-Z,a-z]*)} "Tcl Tutorial" a b puts "Full Match: $a" puts "Sub Match1: $b"
执行以上代码后,将产生以下输出-
Full Match: Tcl Sub Match1: Tcl
以下示例显示了如何搜索多种模式。这是任何字母后跟任何字符后跟任何字母的示例模式。
#!/usr/bin/tclsh regexp {([A-Z,a-z]*).([A-Z,a-z]*)} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c"
执行以上代码后,将产生以下输出-
Full Match: Tcl Tutorial Sub Match1: Tcl Sub Match2: Tutorial
上面代码的修改版显示一个子模式可以包含多个模式,如下所示-
#!/usr/bin/tclsh regexp {([A-Z,a-z]*.([A-Z,a-z]*))} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c"
执行以上代码后,将产生以下输出-
Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial
Tcl中可用的参数列表为:
nocase - 用于忽略大小写。
indices - 存储匹配的子模式的位置而不是匹配的字符。
line - 新的行敏感匹配。忽略换行符。
start index - 设置搜索模式起始的偏移量。
在上面的示例中,无涯教程故意对所有字母使用[A-Z,a-z],您可以轻松地使用-nocase代替如下所示-
#!/usr/bin/tclsh regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c puts "Full Match: $a" puts "Sub Match1: $b" puts "Sub Match2: $c"
执行以上代码后,将产生以下输出-
Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial
另一个示例如下所示-
#!/usr/bin/tclsh regexp -nocase -line -- {([A-Z]*.([A-Z]*))} "Tcl\nTutorial" a b puts "Full Match: $a" puts "Sub Match1: $b" regexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} "Tcl\nTutorial" a b puts "Full Match: $a" puts "Sub Match1: $b"
执行以上代码后,将产生以下输出-
Full Match: Tcl Sub Match1: Tcl Full Match: Tutorial Sub Match1: Tutorial
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)