2016-10-01 68 views
2

在REGEXP中執行包含類似^|.的替換時,如果第一個字符匹配,sed與模式空間開頭的空字符串不匹配。如果最後一個字符匹配,它也不匹配結束。這是爲什麼?

下面是使用123作爲輸入(與-r選項)一些例子:

substitution expected output  actual output comments 
s/^/x/g   x123    x123   works as expected 
s/$/x/g   123x    123x   works as expected 
s/^|$/x/g  x123x    x123x   works as expected 
s/^|./x/g  xxxx    xxx    didn't match the very begining 
s/.|$/x/g  xxxx    xxx    didn't match the very end 
s/^|1/x/g  xx23    x23    didn't match the very begining 
s/^|2/x/g  x1x3    x1x3   this time it did match the begining 

我使用的\`代替^時得到相同的結果。
我試過GNU sed的版本4.2.1和4.2.2

Try it online!

回答

4

AFAIK的sed將嘗試在交替匹配最長的比賽。

因此,當在模式空間的開始空串可以匹配與1在相同的位置。 1被選中,因爲它是最長的一場比賽。

考慮以下幾點:在到達終點時

$ sed 's/12\|123/x/g' <<< 123 
x 
$ sed 's/123\|12/x/g' <<< 123 
x 
$ sed 's/^1\|12/x/g' <<< 123 
x3 

同樣適用。讓我們打破sed 's/.\|$/x/g' <<< 123往下:

123 
^ 
. matches and replace with x 
x23 
^ 
. matches and replace with x 
xx3 
^
    . matches and replace with x 
xxx 
^
    Out of pattern space $ will not match. 
+0

因此,它不會將空字符串視爲在自己的位置?它是第一個角色的一部分? – Riley

+0

'^'表示匹配空字符串,匹配長度爲0,而第一個位置的「1」長度爲1.這樣就被替換了。兩者將相匹配,但只有最長的將被替換。 – andlrc

+0

爲什麼它們都不被替換?儘管'123'更長,'sed's/12 \ | 123/x/g <<< 12123'取代了'12'和'123'。 – Riley

相關問題