tcl 正则表达式

tcl regex expression

regex {func(\(.*\))} "func(test)" a b
puts $a $b

我无法在 b 中进行测试,并且 a 打印 func(test)

我原以为 a 是 func,b 是 test。 我是 tcl 的初学者,tcl 中正则表达式的任何好的资源。谢谢。

要按字面匹配括号,您必须对它们进行转义。未转义的括号是正则表达式分组函数。

regexp {func\((.*)\)} "func(test)" a b

参考:re_syntax

如果你想让变量 "a" 保存 "func" 并且变量 "b" 保存 "test",你必须捕获左括号之前的所有文本和所有括号之间的文本。 这里有2种方法

  1. 使用非贪婪量词:

    regexp {^(.+?)\((.+?)\)} "func(test)" -> a b
    
  2. 使用 "negative" 匹配(扩展正则表达式以提高可读性:

    regexp -expanded {
        ^ ( [^(]+ )    # from start of string, all non-open-parenthesis chars
        \(             # a literal open parenthesis
        ( [^)]+ )      # all non-close-parenthesis chars
        \)             # a literal close parenthesis
    }  "func(test)" -> a b
    

-> 是一个看起来很奇怪但有效的 Tcl 变量,它包含正则表达式匹配的所有文本。在这两个示例中:

puts "$a => $b"    ;# func => test