2016-06-20 156 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 
%