如何用正则表达式获取R中包含数字的单词?

时间:2018-07-02 12:52:50

标签: r

我有一个数据框,其中某些行包含单词“ Comments(0)”。我想获得所有出现“注释”且括号内为任何数字的事件。

我正在使用下面的代码,该代码为我提供integer(0)作为输出。

text <- c("Because I could not Comments(2) stop for Death - Comments(1)",
      "He kindly stopped for me -",
      "The Carriage held but just Ourselves - Comments(5)",
      "and Immortality")

grep(pattern = "Comments([:digit:])", text)

1 个答案:

答案 0 :(得分:0)

您可以使用:

grep(pattern = "Comments\\(\\d\\)", text)
#output
[1] 1 3

grep(pattern = "Comments\\([[:digit:]]\\)", text)

()是正则表达式特殊字符

\\d-数字