Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string matches a certain pattern in tcsh

Tags:

tcsh

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!

like image 310
Sebők Dávid Avatar asked May 17 '15 18:05

Sebők Dávid


1 Answers

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.

like image 148
twalbaum Avatar answered Nov 17 '22 00:11

twalbaum