2017-06-18 92 views
0

誰能解釋如何圖案被發現在這裏grepl和GSUB是罰款了here.But模式不容易理解不清楚正則表達式模式

if (grepl("\\(.*?\\)", name)){  
    gsub("^.*?\\((.*?)\\)$", "\\1", name) 
}  
+0

它們使用[regular exp (https://en.wikipedia.org/wiki/Regular_expression),除非你設置參數fixed = TRUE,在這種情況下,他們只是在字符向量內搜索模式字符串(因爲它是)。 – digEmAll

回答

0

\\(* \\?):

\\ -> \ 
    (-> (
    . -> . 
    * -> zero ore more times the last character 
     ? -> last item is optional (not needed here) 
     \\ -> \ 
     ) ->) 

所以這得到所有字符串像\(\)\(.\)\(....\)

^。 ?\\(?()\\)$:

^.*?\\((.*?)\\)$ 
^ -> Beginning of line 
. -> . 
    * -> zero or more times last item 
    ? -> optional last item (not needed here) 
    \\ -> \ 
     ((. -> ((. 
      * -> zero or more times 
      ? -> optional last item 
      )\\ ->)\ 
       $ -> End of line 

請參閱R documentation正則表達式。

0

檢查出regex101爲您的模式的詳細說明。

"字符"字面上(區分大小寫) \\字符\字面上匹配(區分大小寫) 第一捕獲組(.*?\\) .*?匹配的任何字符(除了行終止) *?量詞匹配 - 零和無限之間的匹配次數越少越好(懶惰) \\字符匹配\(區分大小寫)