代码之家  ›  专栏  ›  技术社区  ›  Carl Witthoft

r函数history()不接受我的模式regexp

  •  1
  • Carl Witthoft  · 技术社区  · 7 年前

    我尝试了一种模式来拒绝任何以0到N个空格开头,后跟一个“”的行。AT this test webpage ,以下模式工作正常:

    ^(?!(\s*[#])).*
    

    我用以下文字作为测试行:

     #tbadword
        #test
    one two
      abadwo#rds
    #three
    

    只选择“非注释”行。
    但在 R ,使用窗口 Rgui ,如果我尝试

    > history(Inf, pattern = '^(?!(\\s*[#])).*' ) 
    

    我收到错误消息“invalid regexp”。

    有人能指出什么吗 R 对这里不满意吗?我需要设置一个全局的“perl=true”或类似的东西吗?还是有一个更简单的方法?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Wiktor Stribiżew    7 年前

    你可能有R history 用pcre regex引擎分析regex:

    history(Inf, pattern="^(?!\\s*#)", perl=TRUE)
    

    现在, ^(?!\s*#) 将正确解析为

    • ^ -字符串开头
    • (?!\s*#) -如果在当前位置的右侧(即字符串的开头)有0+个空格,然后 # .

    虽然 solution with invert=TRUE and an opposite regex 对于当前场景来说更自然,对于其他情况,您可能需要更高级的regex功能,以及 perl=TRUE 将有助于覆盖它们。

        2
  •  2
  •   MrFlick    7 年前

    这个 history() 命令有一个 ... 对于将传递给 grep() ,这样您就可以使用 invert= 标记而不是展望未来以找到你需要的。怎么样

    history(Inf, pattern="^\\s*#", invert=TRUE)