2016-06-20 3 views
1

ユーザー入力をファイルに追加するコードを作成していますが、ユーザーが空白だけを入力し、何も入力しない場合はというイベントをキャッチします。それ、どうやったら出来るの?現在、私はハードコーディング ""と ""があります。これは、ユーザーが1つの空白または2つの空白を入力した場合にキャッチしますが、私よりも優れたソリューションがあると思います。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 -strict $inputs 

string is space $inputs 

が空でない空白文字列を受け入れるには結果はtrue(= 1)またはfalse(= 0)です。

ドキュメント:string

+0

これは、この種のもののための検査の標準的な方法です。 –

2

あなたはの開始マッチし、{^ \ sの+ $}のような正規表現を使用することができます文字列の後に1つ以上の空白(スペースまたはタブ)が続き、文字列の最後まで続きます。だからあなたの例では:

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 
% 
関連する問題