考虑这个简单的例子
dataframe <- data_frame(text = c('WAFF;WOFF;WIFF200;WIFF12',
'WUFF;WEFF;WIFF2;BIGWIFF'))
> dataframe
# A tibble: 2 x 1
text
<chr>
1 WAFF;WOFF;WIFF200;WIFF12
2 WUFF;WEFF;WIFF2;BIGWIFF
在这里,我要提取包含
WIFF
的单词,也就是说,我要以这样的数据框结尾> output
# A tibble: 2 x 1
text
<chr>
1 WIFF200;WIFF12
2 WIFF2;BIGWIFF
我尝试使用
dataframe %>%
mutate( mystring = str_extract(text, regex('\bwiff\b', ignore_case=TRUE)))
但这只会重新调整NA。有任何想法吗?
谢谢!
最佳答案
您似乎想删除所有包含WIFF
和尾随;
的单词(如果有的话)。用
> dataframedataframe <- data.frame(text = c('WAFF;WOFF;WIFF200;WIFF12', 'WUFF;WEFF;WIFF2;BIGWIFF'))
> dataframe$text <- str_replace_all(dataframe$text, "(?i)\\b(?!\\w*WIFF)\\w+;?", "")
> dataframe
text
1 WIFF200;WIFF12
2 WIFF2;BIGWIFF
模式
(?i)\\b(?!\\w*WIFF)\\w+;?
匹配:(?i)
-不区分大小写的内联修饰符\\b
-单词边界(?!\\w*WIFF)
-否定的超前查询将在单词中包含WIFF
的任何匹配项均失败\\w+
-1个或多个字字符;?
-可选的;
(?
匹配1或0次其修改的模式)如果出于某些原因要使用
str_extract
,请注意您的正则表达式将无法正常运行,因为\bWIFF\b
matches a whole word WIFF以及其他所有功能都无法使用。 DF中没有这样的单词。您可以使用"(?i)\\b\\w*WIFF\\w*\\b"
匹配内部带有WIFF
的任何单词(不区分大小写),并使用str_extract_all
多次出现,并且不要忘记将匹配项组合成单个“字符串”:> df <- data.frame(text = c('WAFF;WOFF;WIFF200;WIFF12', 'WUFF;WEFF;WIFF2;BIGWIFF'))
> res <- str_extract_all(df$text, "(?i)\\b\\w*WIFF\\w*\\b")
> res
[[1]]
[1] "WIFF200" "WIFF12"
[[2]]
[1] "WIFF2" "BIGWIFF"
> df$text <- sapply(res, function(s) paste(s, collapse=';'))
> df
text
1 WIFF200;WIFF12
2 WIFF2;BIGWIFF
您可以通过将
str_extract_all
放入sapply
函数中来“缩小”代码,我将它们分开以提高可视性。