Check if a string matches a certain pattern in tcsh

Sebők Dávid picture Sebők Dávid · May 17, 2015 · Viewed 10.2k times · Source

I try to match a user-typed string with a specific pattern, to be exact i want to check if the string starts with an upper case letter and then continues with any upper, lower-case letter or number. I want to do this in tcsh, I know bash is better to use, but I have to use tcsh.

So basically i want the following in tcsh:

if [[ $name =~ ^[A-Z][A-Za-z0-9]*$ ]]

Here is my code so far:

    #!/bin/tcsh
    set name
    while ( $name == "" )
       echo 'Give an account name!'
       set name = $<
       if ( $name =~ '^[A-Z][A-Za-z0-9*$]' ) then
           echo 'Name accepted!'
       else
           echo 'Not correct format!'
           set name = ""
       endif
    end

I'm continously ending up in the "else" part. Thank you very much for the help!

Answer

twalbaum picture twalbaum · Jun 5, 2015

When using the =~ comparison operator, the right hand side must be a pattern that may include asterisk or question mark wildcards (as in file matching) but not RegEx.

This is a workaround I came up with...

#!/bin/tcsh
set name
while ( $name == "" )
    echo 'Give an account name!'
    set name = $<

    set cond = `expr $name : '^[A-Z][A-Za-z0-9]*$'`
    set n = `echo $name | wc -c`
    @ n--

    if ( $cond == $n ) then
        echo 'Name accepted!'
    else
        echo 'Not correct format!'
        set name = ""
    endif
end    

Note that the regular expression also needed fixing.