检查字符串是否与 tcsh 中的特定模式匹配

Check if a string matches a certain pattern in tcsh

我尝试将用户键入的字符串与特定模式匹配,确切地说,我想检查字符串是否以大写字母开头,然后以任何大写、小写字母或数字继续。我想在 tcsh 中执行此操作,我知道 bash 更好用,但我必须使用 tcsh。

所以基本上我想要 tcsh 中的以下内容:

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

到目前为止,这是我的代码:

    #!/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

我一直在 "else" 部分结束。 非常感谢您的帮助!

使用 =~ 比较运算符时,右侧必须是可以包含星号或问号通配符(如在文件匹配中)但不包含 RegEx 的模式。

这是我想出的解决方法...

#!/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    

请注意,正则表达式也需要修复。