尝试使用grepl函数像匹配一样过滤第一个、中间和最后一个字符串单词的数据,但它也选择像HEV和DEV(预期匹配)这样的单词。
Airport_ID<-c("3001","3002","3003","3004")
Airport_Name<-c("DEV Adelaide DTSUpdated","HEV Brisbane HEV Land Airport Land ADTS",
"DEVAST Washington INC Airport DTSUpdated","DALLAS DEVASTAirport HEV INCUpdated")
dfu<-data.frame(Airport_ID,Airport_Name)
Filter_Data_F <- dfu %>%
dplyr::filter(grepl("^DEV" , Airport_Name , fixed = F) |
grepl(" \\DEV\\ " , Airport_Name , fixed = F) |
grepl("DEV$" , Airport_Name , fixed = F) )发布于 2022-07-24 00:41:03
\\D在正则表达式中有着特殊的意义。它匹配任何不是数字字符的字符。因此,在第二个条件下,它是匹配一个非数字字符(H),然后是EV,因此在输出中得到HEV。
其次,在默认情况下,grepl有fixed = FALSE,因此您可以忽略该参数。
另外,我不确定是否应该用grepl编写单独的|参数。只有一个grepl应该这样做。
library(dplyr)
dfu %>% dplyr::filter(grepl('DEV', Airport_Name))
# Airport_ID Airport_Name
#1 3001 DEV Adelaide DTSUpdated
#2 3003 DEVAST Washington INC Airport DTSUpdated
#3 3004 DALLAS DEVASTAirport HEV INCUpdated如果您希望完全匹配DEV,以使DEVAST不匹配,请使用单词边界(\\b)。
dfu %>% dplyr::filter(grepl('\\bDEV\\b', Airport_Name))
# Airport_ID Airport_Name
#1 3001 DEV Adelaide DTSUpdatedhttps://stackoverflow.com/questions/73094998
复制相似问题