TCL:如何从字符串中删除所有 letters/numbers?

TCL: How to remove all letters/numbers from a string?

我正在使用 tcl 编程语言并尝试从字符串中删除所有字母或数字。从 this example,我知道从字符串 (e.x. set s abcdefg0123456) 中删除所有字母的一般方法是

set new_s [string trim $s "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXXYZ"]

如果我想删除字符串中的所有数字,我可以这样做

set new_s [string trim $s "0123456789"]

是否有更直接的方法来删除所有 letters/numbers?

我还注意到,如果我想删除部分数字 (e.x.012) 而不是所有数字,则以下操作不起作用。

set new_s [string trim $s "012"]

谁能解释为什么?

使用正则表达式:

set s abcdefg0123456
regsub -all {\d+} $s {} new_s ;# Remove all digits
regsub -all {[[:alpha:]]+} $s {} new_s ;# Remove all letters

回答您的其他问题:string trim(以及 string trimleftstring trimright 作为“半”版本)删除 set 个来自字符串 ends 的字符(以及 returns 新字符串;它是一个纯功能操作)。它对字符串的内部没有任何作用。它对模式一无所知。默认删除的字符集是“空白”(空格、换行符、制表符等)

当你这样做时:

set new_s [string trim $s "012"]

您正在将移除集设置为 012,但仍然只有末端被移除。因此它将 x012101210y 完全独立,但将 012101210 变成空字符串。