2016-11-22 25 views
0

好奇,想知道爲什麼下面不工作的性質:+BASH =〜包含子: 「+」 或正則表達式字符行爲

人物「\」「(」「*」有道理即*將擴大到文件夾/文件在當前目錄(命令行shell擴展時),同樣\將希望關閉性格的工作,但我的理解是「+」應該像「 - 」一樣工作。

PS:我知道在IF語句中放置雙引號,即「$ {o}」,將適用於下面我測試用例中的所有字符。在帶有或不帶雙引號的IF語句中使用\ $ {o}將會失敗所有檢查。

$ for o in - + \` ~ \~ , _ =/\\ ! @ \# $ \$ %^\& \* \(\); do a="a${o}b${o}c";if [[ $a =~ ${o} ]]; then echo "${o} exists in $a and =~ works"; else echo -e "\ncharacter ${o} doesn't work with =~\n"; fi; done 
- exists in a-b-c and =~ works 

character + doesn't work with =~ 

` exists in a`b`c and =~ works 
/home/ubuntu exists in a/home/ubuntub/home/ubuntuc and =~ works 
~ exists in a~b~c and =~ works 
, exists in a,b,c and =~ works 
_ exists in a_b_c and =~ works 
= exists in a=b=c and =~ works 
/exists in a/b/c and =~ works 

character \ doesn't work with =~ 

! exists in a!b!c and =~ works 
@ exists in [email protected]@c and =~ works 
# exists in a#b#c and =~ works 
$ exists in a$b$c and =~ works 
$ exists in a$b$c and =~ works 
% exists in a%b%c and =~ works 
^ exists in a^b^c and =~ works 
& exists in a&b&c and =~ works 

character * doesn't work with =~ 


character (doesn't work with =~ 

) exists in a)b)c and =~ works 
+1

沒有'*'不擴展到文件列表 - 在正則表達式中,它意味着「零或多個前面的標記」。 –

+0

@CharlesDuffy正確,我的意思是「for」聲明。 –

+0

......但是你爲'for'語句轉義爲'\ *',所以它沒有在那裏做任何這樣的替換。 –

回答

3

這個問題背後的根本誤解是=~是一個子串搜索運算符。 這不是

=~的右側被評估爲POSIX ERE表達式。因此,=~是一個正則表達式匹配運算符,當引用右側引用其內容時(或者在解釋爲ERE時知道該字符串本身僅匹配自身)時,經常用於搜索。


+,在正則表達式,是指「1或更多的前述令牌的」 - 正如*表示「0或更多的前述令牌」。

因此,無論是[[ $foo =~ + ]][[ $foo =~ * ]]是沒有意義的,因爲這些檢查零或更多的的一個在先令牌並不以所有存在。

同樣,()在ERE中作爲匹配組的開始和結束有意義,所以當它們被裸露(未轉義/未被引用)時,它們會導致無效的正則表達式。

如果引用擴展,相比之下,包含的所有字符將被視爲文字,而不是被視爲正則表達式元字符,從而導致可能的預期行爲。


如果你想檢查文字字符是否包含在一個字符串,要麼報價吧 - [[ $foo =~ "$o" ]] - 或使用通配符式樣的模式:[[ $foo = *"$o"* ]]

相關問題