We help IT Professionals succeed at work.

Need more better and efficient solutions for useing regular expressions to validate  the user input in csh?

Jerryleo
Jerryleo asked
on
Medium Priority
288 Views
Last Modified: 2010-04-22
I need some comments to get a more better and efficient solution for validating the user  input in a  csh script.  

Here are my solutions

#last two digits of year (00..99)
if ( `echo $Yr | grep '^[0-9][0-9]$'` == '' ) then
        echo INVALID Yr;exit 1
 endif
 
#day of year (001..366)
 if ( `echo $Doy | grep '^[0-2][0-9]\{2\}$'` == '' && \
           `echo $Doy | grep '^3[0-6]\{2\}$'`     == '' || \
           $Doy == '000' ) then
        echo INVALID Doy;exit 1
 endif

 #4-character site ID (can contain only letters, numbers)
 if ( `echo $Site | grep '^[a-zA-Z0-9]\{4\}$'` == '' ) then
        echo INVALID SiteID;exit 1
 endif

#1-character session ID (can contain only 0 or letters a-x)
 if ( `echo $SessID | grep '^[0|a-xA-Z]$'` == ''  ) then
        echo INVALID SessID;exit 1
 endif

Any comments will be appreciated

Thanks
Comment
Watch Question

* For the first expression, you can also use:
^[0-9]{2}$  , it's shorter

* For the day of year:

(if you want to take into account the leap years, you'd need to do more calculations)

if you want  1 ... 366 format you can use this regular expression:

^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$

This would allow more accurate checking of the day.

* The expression for the 1 char ID is wrong:
^[0|a-xA-Z]$   ---> change to this:   ^[0a-xA-X]$

Author

Commented:
Thanks for reply

>^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$

It doesn't work. for example,
[jerry@beks-m04 ~]$ echo 203 | grep '^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$'
[jerry@beks-m04 ~]$

Yes, because you're using grep.
Try using egrep, that one does regular expression matching.
Or try grep -E


drk@nevermore / $ echo 203 | grep "^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$"
drk@nevermore / $ echo 203 | egrep "^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$"
203
drk@nevermore / $ echo 203 | grep -E "^(36[0-6]|3[0-5][0-9]|[1-2][0-9]{2}|[1-9][0-9]|[1-9])$"
203

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.