-1

Please help. How to make regex work in an if condition, to check user input(in 2nd parameter) must be not equal to any number?

set regex="^[0-9]+$"
if ($#argv == 2 && $2 != $regex) then
# do this
user68890
  • 69
  • 1
  • 4
  • 10

1 Answers1

0

grep-based solution that only works for non-negative integers.

#!/bin/csh

# Note this requires 2 command line arguments, and checks the second one
# cshell arguments are 0-indexed.
if ($#argv == 2) then

    # Note the different grep regexp syntax, and you must use single quotes
    set test = `echo $2 | grep '^[0-9]*$'`
    if (($test) || ($test == 0)) then
        echo "Bad input"
    else
        echo "Ok!"
    endif
endif
supergra
  • 1,578
  • 13
  • 19
  • hi this works fine! but then, it wont include 0. any idea why? but if i put `^[-0-9]*$` it includes negative numbers, but still not 0. thats the only prob now but thanks! kindly help me still if u know the solution thanks! – user68890 Nov 03 '14 at 08:32
  • It won't include 0 because 0 evaluates to "False" in the the segment `if ($test)`. – supergra Nov 04 '14 at 17:08
  • what i did was i put -c option in grep, and retained the rest of the code and it seemed to be working. learned that -c is count, idk but do u think its safe to use the -c option? like this: set test = `echo $2 | grep -c '^[0-9]*$'` – user68890 Nov 05 '14 at 01:51
  • Looks pretty safe to me. Just remember that neither my solution nor your '-c' idea will match decimals. For that, you need a more complicated regexp. – supergra Nov 05 '14 at 22:39
  • its okay, wont include decimals. Thanks!! :) – user68890 Nov 06 '14 at 00:58