是否有一个R函数来查找字符向量中的regexp匹配索引? [英] Is there an R function to find the index of regexp matches in a character vector?

查看:65
本文介绍了是否有一个R函数来查找字符向量中的regexp匹配索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个R函数,该函数的作用类似于 match ,仅用于正则表达式匹配而不是相等.换句话说,如果我有一个变量 r 是正则表达式的字符向量,而变量x是一个字符向量,则我希望该函数返回与 r ,它为每个正则表达式提供与该正则表达式匹配的第一个元素的索引.请注意,我不希望正则表达式匹配的字符串中的位置.我想要与每个正则表达式匹配的 element 的索引.

I'm looking for an R function that works like match only for regular expression matching instead of equality. In other words, if I have a variable r that is a character vector of regular expressions and a variable x which is a character vector, I want the function to return a numeric vector the same length as r that gives, for each regular expression, the index of the first element that matches that regular expression. Note that I don't want the position within the string where the regular expression matches. I want the index of the element that matches each regular expression.

推荐答案

您只是在寻找 grep :

x <- c("arm","foot","lefroo", "bafoobar")
r <- c("ar","^ba","$m","foo")

获取第一个正则表达式匹配索引:

Get the first regex match index:

sapply(r, function(y) grep(y,x)[1])

 ar ^ba  $m foo 
  1   4  NA   2 

获取所有正则表达式匹配索引:

Get all regex match indexes:

sapply(r, function(y) grep(y,x))

$ar
[1] 1 4 # returns matches of ar in x

$`^ba`
[1] 4

$`$m`
integer(0)

$foo
[1] 2 4

这篇关于是否有一个R函数来查找字符向量中的regexp匹配索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆