tcl - How to check that the string is single word? -


how check string single word?

is right way that?

set st "some string"  if { [llength $st] != 1 } {    puts "error" } 

my answer based on assumption word contains alphabet characters.

if don't mind using regexp, can use this:

set st "some string"  if { ![regexp {^[a-za-z]+$} $st] } {    puts "error" } 

[regexp expression string] returns 0 if there no match , 1 there match.

the expression used ^[a-za-z]+$ means string starts letter , can contain number of letters , must end letter. if want include dash inside (e.g. co-operate 1 word), add in character class:

^[a-za-z-]+$

if worried trailing spaces, suggest trimming first before passing regexp:

set st "  string  "  if { ![regexp {^[a-za-z]+$} [string trim $st]] } {    puts "error" } 

or if want directly use regexp...

set st "  string    "  if { ![regexp {^\s*[a-za-z]+\s*$} $st] } {    puts "error" } 

edit: if word considered string of characters except space, can else: check if string contains space.

set st "some strings"  if { [regexp { } $st] } {    puts "error" } 

if finds space, regexp return 1.


Comments