2016-06-20 157 views
1

我正在建立一个代码,以添加用户输入到一个文件,但我想捕捉一个事件,其中用户只输入空白,没有别的。我怎么做?目前我是硬编码“”和“”,如果用户输入一个空格或两个空白符号,它会被捕获,但我相信有比我更好的解决方案。TCL检查只有空格

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 

回答

8

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

string is space $inputs 

要接受空白字符串不是空:

string is space -strict $inputs 

结果是真(= 1)或假(= 0)。

文档:string

+0

这是测试对这种事情的规范的方法。 –

2

您可以使用正则表达式如{^ \ S + $},它匹配开始的字符串仅由一个或多个空格(空格或制表符)组成,直到字符串结尾。因此,在你的例子:

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

如果你想在同一个表达式来检查所有空白空字符串,使用{^ \ S * $}。

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

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 
%