Home > Software design >  TCL regexp matches strings that are all lower case
TCL regexp matches strings that are all lower case

Time:08-25

I am using regexp to ensure the string is all lower case,but it seems not useful.

Here's my code

set name aAaaaA
if { [regexp {/^[a-z]$g} $name] } {
   puts "continue"
} else {
   puts "String is not lowercase. Please enter again"
}

I need to ensure the input is all lowercase ,and without any uppercase,symbol

And I've found [regexp (?=.*[\L]) $name] can express characters other than lowercase letters,but it's not useful,too.

Can anyone help for this? Thanks!

CodePudding user response:

There is no need to use regexp for this. Tcl has a command to check if a string matches some predefined character class. Lowercase is one of the predefined classes:

set name aAaaaA
if {[string is lower $name]} {
   puts "continue"
} else {
   puts "String is not lowercase. Please enter again"
}

You can add the -strict option if you don't want to accept the empty string: string is lower -strict $name

CodePudding user response:

You can use

set name aAaaaA
if { [regexp {^[[:lower:]] $} $name] } {
   puts "continue"
} else {
   puts "String is not lowercase. Please enter again"
}

See the Tcl demo.

If an empty string is valid, replace with *.

More details:

  • ^ - start of string
  • [[:lower:]] - one or more lowercase letters
  • $ - end of string.

CodePudding user response:

I'd check whether any of the bad characters (upper case) are present:

if {[regexp {[[:upper:]]} $name]} {
    puts "String is not lowercase. Please enter again"
} else {
    puts "continue"
}

A good trick with regular expressions is that it is often easier to look for the inverse of what you're really after; instead of looking to see if the string is good, look to see if it is bad.

  • Related