不清楚的正则表达式模式

时间:2017-06-18 07:16:26

标签: r grepl

有谁可以解释一下如何在这里找到模式?grepl和gsub在这里很好。但模式不容易理解

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

查看regex101以获取有关模式的详细说明。

"字面匹配字符"(区分大小写) \\字面匹配字符\(区分大小写) 第一捕获组(.*?\\) .*?匹配任何字符(行终止符除外) *?量词 - 在零和无限时间之间匹配,尽可能少,根据需要扩展(懒惰) \\字面匹配字符\(区分大小写)