我想检查这些字符串的字符串模式:
1) name.
2) name.{j}.
3) name.{j}.name.{i}.
4) name.{j}.name.{i}.param
如何检查字符串1是否仅以"."
[模式1]
如何检查字符串2是否仅以".{j}."
[模式2]
如何检查字符串3是否包含".{j}."
并仅完成[模式3] ".{j}."
如何检查字符串4是否包含".{j}."
并仅以".{j}.string"
完成[模式4]
这是将要使用的proc的模式
proc check_patern {string} { /* if string match the pattern 1*/ set res [check string $pattern1 $string] if {res ==1} puts "string match pattern 1" /* elseif string match the pattern 2*/ set res [check string $pattern2 $string] if {res ==1} puts "string match pattern 2" /* elseif string match the pattern 3*/ set res [check string $pattern3 $string] if {res ==1} puts "string match pattern 3" /* elseif string match the pattern 4*/ set res [check string $pattern4 $string] if {res ==1} puts "string match pattern 4" }
答案 0 :(得分:0)
你走了。模式可以压缩为单个正则表达式:
set pattern {\w+\.(?:\{[ij]\}\.(?:\w+)?)?$}
# or, expanded with comments
set pattern {(?x)
\w+\. # a word followed by a dot
(?:\{[ij]\}\. # optionally followed by "{j}."
(?:\w+)? # which is optionally followed by a word
)? #
$ # anchored at the end of the string
}
set lines {
"0) do not match me"
"1) name."
"2) name.{j}."
"3) name.{j}.name.{i}."
"4) name.{j}.name.{i}.param"
"5) name.{j}"
}
foreach line $lines {
if {[regexp $pattern $line]} {puts $line}
}
输出第1-4行,而不是第0行或第5行