2014-10-20 541 views
-1

請幫忙。如何使正則表達式在if條件下工作, 檢查用戶輸入(在第二個參數中)必須不等於任何數字?正則表達式 - 檢查輸入是否是csh中的數字(unix)

set regex="^[0-9]+$" 
if ($#argv == 2 && $2 != $regex) then 
# do this 
+0

TRy this'if [$#argv == 2 &&! $ 2 =〜$ regex]' – 2014-10-20 02:31:18

+0

嗨,我試過,但即時得到「**可變語法**」錯誤。 – user68890 2014-10-20 02:44:53

+0

'... &&! $ 2 =〜「$ regex」] ...''? (注意'regex'變量周圍的dbl引號,很抱歉,但我沒有辦法測試它)。祝你好運。 – shellter 2014-10-20 03:36:03

回答

0

grep的基礎解決方案僅適用於非負整數

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

嗨,這工作正常!但是,它不會包含0.任何想法爲什麼?但是如果我把'^ [ - 0-9] * $'包含負數,但仍然不是0.那是現在唯一的概率,不過謝謝!好心幫助我,如果你知道解決方案,謝謝! – user68890 2014-11-03 08:32:20

+0

它不包含0,因爲0在段落if($ test)'中的值爲「False」。 – supergra 2014-11-04 17:08:22

+0

我編輯它以包含零。 – supergra 2014-11-04 17:24:42

相關問題