TCL只检查空格

时间:2016-06-20 03:34:28

标签: tcl whitespace

我正在构建一个代码来将用户输入添加到文件中,但是我想要捕获一个用户只输入空格而没有其他内容的事件。我怎么做?目前我正在硬编码“”和“”,如果用户输入一个空格或两个空格,它会被捕获,但我相信有一个比我更好的解决方案。

Proc将用户输入插入文本文件

proc inputWords {entryWidget} {
set inputs [$entryWidget get]
$entryWidget delete 0 end
if {$inputs == ""} {
.messageText configure -text "No empty strings"
} elseif {$inputs == " " || $inputs == "  "} {
.messageText configure -text "No whitespace strings"
} else {
set sp [open textfile.txt a]
puts $sp $inputs
close $sp
.messageText configure -text "Added $inputs into text file."
}
}

GUI代码

button .messageText -text "Add words" -command "inputWords .ent"
entry .ent
pack .messageText .ent

3 个答案:

答案 0 :(得分:8)

接受任意长度的空格字符串,包括0:

string is space $inputs

接受不空的空白字符串:

string is space -strict $inputs 

结果为true(= 1)或false(= 0)。

文档:string

答案 1 :(得分:2)

您可以使用正则表达式,如{^ \ s + $},它匹配字符串的开头,后跟一个或多个空格(空格或制表符),直到字符串的结尾。所以在你的例子中:

elseif {[regexp {^\s+$} $inputs]} {
  .messageText configure -text "No whitespace strings"
...

如果要检查同一表达式中的所有空格空字符串,请使用{^ \ s * $}。

有关TCL中正则表达式的更多信息,请参阅http://wiki.tcl.tk/396。如果这是您第一次接触正则表达式,我建议您在线寻找正则表达式教程。

答案 2 :(得分:2)

假设您想要关闭用户输入的前导和尾随空格,您可以修剪字符串并检查零长度。性能方面,这是更好的:

% set inputs "    "

% string length $inputs
4
% string length [string trim $inputs]
0
% 
% time {string length [string trim $inputs]} 1000
2.315 microseconds per iteration
% time {regexp  {^\s+$} $inputs} 1000
3.173 microseconds per iteration
% time {string length [string trim $inputs]} 10000
1.8305 microseconds per iteration
% time {regexp  {^\s+$} $inputs} 10000
3.1686 microseconds per iteration
% 
% # Trim it once and use it for calculating length
% set foo [string trim $inputs]
% time {string length $foo} 1000
1.596 microseconds per iteration
% time {string length $foo} 10000
1.4619 microseconds per iteration
% 
相关问题