简体   繁体   English

如何将表达式的开头和结尾与R中的grep进行匹配

[英]how to match the start and end of an expression with grep in R

I am trying to match the start and end of expressions with grep command, but I am not able to do that. 我试图用grep命令匹配表达式的开始和结束,但我无法做到这一点。 for example consider the following expressions. 例如,考虑以下表达式。

filenames <- c("S2abc.6h", "S2abc.4h", "S2abc.0h","S4abc.6h","S2xyz.6h")

I want to fins all the files starting with S2 and ending with 6h. 我想要以S2开头并以6h结束的所有文件。 I can select the files starting with S2 using: 我可以使用以下方式选择以S2开头的文件:

grep("S2", filenames, value = TRUE)

But I am not able to use the wild cards with grep. 但我无法使用grep的外卡。

> grep("S2*6h", filenames, value = TRUE)

 character(0)

You can use ^ to determine the start and $ to determine the end of a string. 您可以使用^来确定开始,使用$来确定字符串的结尾。 The .+ catches everything inbetween. .+捕捉中间的一切。

grep("^S2.+6h$", filenames, value = TRUE)
# [1] "S2abc.6h" "S2xyz.6h"

I think your approach to use grep is fine, you only need to slightly tweak the regular expression you use to match the filenames you want. 我认为你使用grep方法很好,你只需要稍微调整你用来匹配你想要的文件名的正则表达式。

> matches <- grep("^S2.*\\.6h$", filenames, ignore.case = T)
> matches
[1] 1 5
> filenames[matches]
[1] "S2abc.6h" "S2xyz.6h"

The regex I used is: 我使用的正则表达式是:

^S2.*\\.6h$

This will match any filename which begins with S2 and ends with .6h 这将匹配任何以S2开头并以.6h结尾的文件名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM