Perl 小知識之多行匹配

若是想匹配多行文本(即文本中有換行符)中的內容,好比:git

1 aaa
2 
3 ...
4 
5 bbb
6 
7 ...

要匹配aaa和bbb之間的內容,咱們能夠使用 /aaa.*bbb/s測試

其中/s修飾符能夠讓.匹配任何字符,包括換行符。lua

不過,除此以外,咱們能夠使用..操做符:spa

/aaa..bbb/scala

就像sed命令同樣:sed -n '/aaa/,/bbb/p' filecode

..操做符叫作區塊運算符(Range Operator) ,這個運算符是 Perl 語言中特有的運算符,是一個很實用的運算符.  blog

好比: three

1 @digits=(1..9); #此時 @digits=(1,2,3,4,5,6,7,8,9);    
2 @digits=('01'..'05'); #此時 @digits=(01,02,03,04,05);    
3 @char=('A'..'E'); #此時 @char('A','B','C','D','E',);    
4 @total=(1..3'A'..'B'); #此時 @total=(1,2,3'A','B');

摘抄一段解釋:ip

In scalar context, ".." returns a boolean value.  The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors.  Each ".." operator maintains its own boolean state.  It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again.  It doesn't become false till the next time the range operator is evaluated.  It can test the right operand and become false on the same evaluation it became true (as in awk), but it still returns true once.  If you don't want it to test the right operand till the next evaluation, as in sed, just use three dots ("...") instead of two.  In all other regards, "..." behaves just like ".." does.it

即..和...的差異在於:當一個..flip-flop爲true時,它會返回true,同時測試它的右側表達式以決定是否須要將其內部狀態設置回false;而對於...flip-flop來講,它等到下一次求值的時候才測試其右側表達式。觀察下面的代碼:

1 (1..10).each {|x| print x if x==3..x>=3}
2 # Prints "3"  .  Flips and flops back  when x==3
3 
4 (1..10).each {|x| print x if x==3...x>=3}
5 # Print "34" .   Flis when x==3 and flops when x==4
相關文章
相關標籤/搜索