【问题标题】:The R-function history() doesn't accept my pattern regexpR-function history() 不接受我的模式正则表达式
【发布时间】:2018-07-06 19:47:54
【问题描述】:

我尝试了一种模式来拒绝任何以 0 到 N 个空格开头的行,然后是 "#" 。在this test webpage,以下模式可以正常工作:

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

我使用以下文本作为测试行:

 #tbadword
    #test
one two
  abadwo#rds
#three

并且只选择“非注释”行。
但是在R,如果我尝试使用Windows Rgui

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

我收到错误消息“无效的正则表达式”。

有人能指出R 对这里的不满吗?我是否需要设置一个全局“perl=TRUE”或类似的东西?或者有没有更简单的方法来做到这一点?

【问题讨论】:

  • @WiktorStribiżew 如何使用str_extract 获取历史记录?我认为str_extract 用于从给定字符串中提取文本。它在这里有什么用处?
  • 我以为 OP 有一个字符串。没关系。 history(Inf, pattern="^(?!\\s*#)", perl=TRUE) 会起作用。

标签: r regex regex-lookarounds


【解决方案1】:

history() 命令有一个... 用于传递给grep() 的值,因此您可以使用invert= 标志而不是前瞻来查找您需要的内容。怎么样

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

【讨论】:

  • ahhh... 傻我没有足够详细地阅读?history(和?grep
【解决方案2】:

您可能让 R history 使用 PCRE 正则表达式引擎解析您的正则表达式:

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

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

  • ^ - 字符串开头
  • (?!\s*#) - 如果紧靠当前位置的右侧(即字符串开头)有 0+ 个空格,然后是 #,则匹配失败。

虽然solution with invert=TRUE and an opposite regex 对于当前场景更自然,但您可能需要更高级的正则表达式功能来应对其他情况,perl=TRUE 将帮助覆盖它们。

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多