2014-10-07 20 views
3

爲什麼轉義角度支架>的轉義表現出前瞻性的行爲?轉角支架的作用類似於前視

要清楚,我知道角架不需要被轉義。
是,如何被解釋模式的問題,它產生出的匹配(ES)

## match bracket, with or without underscore 
## replace with "greater_" 
strings <- c("ten>eight", "ten_>_eight") 
repl <- "greater_" 

## Unescaped. Yields desired results 
gsub(">_?", repl, strings) 
# [1] "tengreater_eight" "ten_greater_eight" 

## All four of these yield the same result 
gsub("\\>_?", repl, strings) # (a) 
gsub("\\>(_?)", repl, strings) # (b) 
gsub("\\>(_)?", repl, strings) # (c) 
gsub("\\>?", repl, strings) # (d) 
gsub("\\>",  repl, strings) # (e) 
# [1] "tengreater_>eightgreater_" "ten_greater_>_eightgreater_" 

gregexpr("\\>?", strings) 

一些跟進的問題:

1. Why do `(a)` and `(d)` yield the same result? 
2. Why is the end-of-string matched? 
3. Why do none of `a, b, or c` match the underscore? 
+0

'\\>'=字邊界.. – 2014-10-07 14:14:54

回答

3

\\>是一個字邊界其中A之間的匹配單詞字符(在左側)和非單詞字符(在右側)或行尾的結尾$

> strings <- c("ten>eight", "ten_>_eight") 
> gsub("\\>", "greater_", strings) 
[1] "tengreater_>eightgreater_" "ten_greater_>_eightgreater_" 

在上面的例子n後一個字字符和非文字字符>然後也t和在所述第一元件的線錨定件的端部之間的邊界之間只存在於字邊界匹配它。並且它匹配_(也是單詞字符)和>之間,然後在t和第二個元素中的行錨點結尾(即$)之間匹配。最後,它會用您指定的字符串替換匹配的邊界。

一個簡單的例子:

> gsub("\\>", "*", "f:r(:") 
[1] "f*:r*(:" 

考慮以下輸入字符串。 (w指字的字符,N意指非字字符

f:r(: 
w___||||| 
    |w|N 
    N | 
     | 
     N 

所以之間\\>火柴,

  • f:
  • r(

實施例2:

> gsub("\\>", "*", "f") 
[1] "f*" 

輸入字符串:

f$ 
||----End of the line anchor 
w 

*更換匹配邊界會得到上述結果。

+0

謝謝Avinash。我熟悉'\ b',但不熟悉'\>'。非常有用,謝謝 – 2014-10-07 20:46:55

相關問題