用grepl替换解析正则表达式 [英] Regular expression parsed with grepl replacement
问题描述
目标是解析正则表达式并替换匹配的模式.
The objective is to parse a regular expression and replace the matched pattern.
请考虑以下示例:
data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
我必须找到所有出现的cat
和一个数字[0-9]
.为此:
I have to locate all occurrences of cat
and a number [0-9]
. To do this:
found <- data[grepl("(^cat.[a-z][0-9])|(^cat.[0-9])",data)]
found
[1] "cat 6kg" "cat g250" "cat 10 kg"
下一步是将found
的每个元素替换为字符串cat
.我已尝试根据堆栈问题20219311从软件包(gsubfn)中尝试 gsub , sub 和 gsubfn():
The next step is to replace each element of found
with string cat
. I have attempted gsub, sub, and gsubfn() from package (gsubfn) according to Stack question 20219311:
gsubfn("((^cat.[a-z][0-9])|(^cat.[0-9]))", "cat",data)
[1] "catkg" "cat50" "cat dog" "cat0 kg"
这不是预期的结果:
[#] "cat" "cat" "cat dog" "cat"
我想我遗漏了一点.我将不胜感激.谢谢.
I think I'm missing a point. I would appreciate any help I could get. Thanks.
推荐答案
简单,只需将字符串cat
分配给match元素.这将用cat
Simple,,,, Just assign the string cat
to the match elements. This will replace all the chars present in the element with cat
> data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
> data[grepl("(^cat.[a-z][0-9])|(^cat.[0-9])",data)] <- "cat"
> data
[1] "cat" "cat" "cat dog" "cat"
或
> data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
> data[grepl("^cat.[a-z]?[0-9]",data)] <- "cat"
> data
[1] "cat" "cat" "cat dog" "cat"
这篇关于用grepl替换解析正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!