2014-10-31 91 views
0

我有這個巴什 - 如何檢查是否字符串包含不止一個特殊cahracter

if [[ ! $newstring == *['!'@#\$%^\&*()_+]* ]] 
then 
    echo Error - Does not contain One Special Character - $newstring 
    i=$((i+1)) 
fi 

,檢查如果字符串只有從銀行一個單個字符,我要檢查,如果有一個以上的?

什麼是最好的方法?

+1

停止編寫自己的密碼複雜度檢查並讓人們使用密碼短語。 – 2014-10-31 16:20:10

+0

我不認爲檢查「one and only one」的測試......末尾的'*'可能包含任何數量的附加「特殊」字符......所以它只檢查「至少一個」.. – twalberg 2014-10-31 18:05:22

回答

2

要麼添加一個第二類

if [[ "$newstring" != *['!'@#\$%^\&*\(\)_+]*['!'@#\$%^\&*\(\)_+]* ]] 

或條別的出來,並檢查長度

t="${newstring//[^[email protected]#\$%^\&*()_+]}" 
if [ ${#t} -lt 2 ] 
+0

你寫的任何理由'[[!! x == y]]'vs'[[x!= y]]'? – 2014-10-31 16:25:58

+0

@glennjackman複製OPs風格,沒有很好的理由。 – 2014-10-31 16:27:08

0
#!/bin/bash 

a='!*@%6789'; 
if [[ `echo $a | sed "s/\(.\)/\1\n/g"|grep -c "[[:punct:]]"` -gt 1 ]]; then echo shenzi; else echo koba; fi 
+2

這需要至少一個子shell和兩個外部命令。 – 2014-10-31 16:28:44

+0

我同意。感謝您指出Etan。 – 2014-10-31 16:38:40

0

grep可以是有用的,以提供匹配

grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$" 

測試

$ echo "#asdfasdf234" | grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$" 

將匹配字符串作爲

#asdfasdf234 

$ echo "#asdf#asdf234" | grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$" 

不會匹配字符串

if結構可以

echo $newstring| grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$" 
if [[ $? -eq 0 ]] > /dev/null 
then 
    echo Error - Does not contain One Special Character - $newstring 
    i=$((i+1)) 
fi 

這裏正則表達式

^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$ 

匹配所有字符串與特定字符的確切出現次數

+0

您是否可以使用[[:punct:]]? – 2014-10-31 16:37:35

+0

@ArunSangal是的,我可以有。剛剛從OPs問題中複製而來。 – nu11p01n73R 2014-10-31 16:43:12

相關問題