vho
vho

Reputation: 1141

How to check that the string is single word?

How to check that string is a single word?

Is this right way to do that?

set st "some string"

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

Upvotes: 1

Views: 1488

Answers (3)

Varun
Varun

Reputation: 691

regexp provides a straight forward way to match a word with \w and \W. \w matches a word character, while \W matches any character except a word character.

set st "some string"
if { [regexp {\W} $st] } {
   puts "error"
}

However \w matches only digits, alphabets and _ (in any combination). If special characters are there in your word, this will not work.

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137577

According to one possible definition, you check if a string is one word by using:

catch {set oneWord 0;set oneWord [expr {[llength $string] == 0}]}

That's the Tcl language definition of a word.

On the other hand, if your preferred definition is “is alphanumeric” then you have other possibilities, such as:

# -strict excludes the empty string (normally included for historic reasons)
set oneWord [string is alnum -strict $string]

Upvotes: 2

Jerry
Jerry

Reputation: 71538

My answer is based on the assumption that a word contains only alphabet characters.

If you don't mind using some regexp, you can use this:

set st "some string"

if { ![regexp {^[A-Za-z]+$} $st] } {
   puts "error"
}

[regexp expression string] returns 0 if there is no match and 1 is there is a match.

The expression I used is ^[A-Za-z]+$ which means the string starts with a letter and can contain any number of letters and must end with a letter. If you want to include a dash inside (e.g. co-operate is one word), you add it in the character class:

^[A-Za-z-]+$

If you are now worried about trailing spaces, I would suggest trimming it first before passing it to the regexp:

set st "  some string  "

if { ![regexp {^[A-Za-z]+$} [string trim $st]] } {
   puts "error"
}

or if you want to directly use the regexp...

set st "  some string    "

if { ![regexp {^\s*[A-Za-z]+\s*$} $st] } {
   puts "error"
}

EDIT: If a word is considered as a string of characters except space, you can do something else: check if the string contains a space.

set st "some strings"

if { [regexp { } $st] } {
   puts "error"
}

If it finds a space, regexp will return 1.

Upvotes: 1

Related Questions