Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中部分匹配的Grep_R_Regex - Fatal编程技术网

R中部分匹配的Grep

R中部分匹配的Grep,r,regex,R,Regex,我可以将我的输入ex与向量str与以下代码匹配 这里的“exp”与str str <- c("Regular", "expression", "examples of R language") x <- grep("exp",str,value=F) My x=“expression”应与str“exp”匹配,结果应为“exp” 有没有办法做到这一点?我们需要提取子字符串。在base R中,可以使用regexpr/regmatches regmatches(str, reg

我可以将我的输入
ex
与向量
str
与以下代码匹配

这里的“exp”与
str

str <- c("Regular", "expression", "examples of R language")    
x <- grep("exp",str,value=F)
My x=“expression”应与str“exp”匹配,结果应为“exp”


有没有办法做到这一点?

我们需要提取子字符串。在
base R
中,可以使用
regexpr/regmatches

regmatches(str, regexpr("exp", str))
#[1] "exp"

或使用
stringr/stringi

library(stringr)
na.omit(str_extract(str, 'exp'))
#[1] "exp"


使用
grep
我们可以发现是否存在分词匹配。它返回元素或逻辑向量的数字索引(使用
grepl
)。使用
value=TRUE
,它返回匹配的元素,而不是部分子字符串

感谢您花时间回复,但您的答案不符合我的要求。我知道如何将“exp”与“expression”匹配,并且我已经用代码编写了它。我想把“表达式”和“exp”匹配起来。请仔细看一下描述。再次感谢。@subharanjansaho好吧,你的描述让人困惑,因为你在某处使用了“exp”,然后使用了“expression”@subharanjansaho在这种情况下,请尝试
substr(regmatches(str,regexpr(“expression”),1,3)#[1]“exp”
或者
grep(substr(“expression”,1,3),str,value=TRUE)[1]“exp”
我是否可以在不执行substr()的情况下将“expression”与“exp”匹配?substr()不是解决方案,因为我无法将其应用于“表达式”之外的任何内容,因为它是硬编码的。请建议是否有其他直接匹配的方式。再次感谢。
library(stringr)
na.omit(str_extract(str, 'exp'))
#[1] "exp"