regex - R - 从文件中读取行的部分匹配

我有一个这样的 file.txt,我想在 R 中读取它直到找到匹配项:

header1
header2
more descriptions
again
stop here
dataline1             
dataline2
dataline3

在这种情况下,匹配将是“停在这里”。

我想通过以下方式做到这一点:

x<-file("file.txt","r")
match<-paste("stop","here")
line<-readLines(x,1)
while(line!=match){
        line<-readLines(x,1)
}

line
[1] "stop here"

问题是停止行可以有更多的字符串,也就是说,除了“在这里停止”之外,还可以像“在这里停止某物”,其中某些东西可以从一个文件到另一个文件发生变化。 当尝试使用上面的代码读取这个新文件时,它会抛出一个错误:

Error in while (line != match) { : argument is of length zero

并且行是空的。

line
character(0)

我试过使用 collapse 和 grep,但出现了同样的错误。

match<-paste("stop","here", collapse = "|")
while(line!=grep(match, line)){

有什么办法可以解决这个问题吗? 谢谢

最佳答案

您可以使用 grepl 而不是 grep 因为它直接返回一个 logical

x <- file("file.txt", "r")
line <- readLines(x, 1)
while(!grepl("^stop here.+", line)) {
    line <- readLines(x, 1)
}

https://stackoverflow.com/questions/29258080/

相关文章:

camunda - 控制部署的 Camunda BPM 的版本

r - 如何动态更改 R 中现有函数的一行

c# - 从 Roslyn 中的方法符号生成方法签名的语法

amazon-web-services - 如何防止使用签名网址从亚马逊云端下载视频

google-app-engine - Google App Engine 删除了默认的 GCS 存

github - 如何查看用户的 github 拉取请求评论列表?

dns - 为 DMARC 等将 DNS IN TXT 记录拆分为多行

portable-executable - 为什么 PE 格式位置依赖?

python - 如何访问图中特定顶点的名称(python-igraph)

c# - 如何在使用 IDataErrorInfo 时检查模型是否有效或有错误