grep在固定= T在R的字符串的开始? [英] grep at the beginning of the string with fixed =T in R?

查看:138
本文介绍了grep在固定= T在R的字符串的开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何grep with fixed = T ,但只在字符串的开头?

  grep(a。,c(ab,cac,sss,ca.f),fixed = T)
#1 4

我只想得到第一个匹配项。


谢谢。


]

解决方案

如果要匹配字符串(字符串2)开始处的确切字符串(字符串1),则只需将字符串2的子集相同即可长度为字符串1并使用==,应该相当快。


How to grep with fixed=T, but only at the beginning of the string?

grep("a.", c("a.b", "cac", "sss", "ca.f"), fixed = T)
# 1 4

I would like to get only the first occurrence. [Edit: the string to match is not known in advance, and can be anything. "a." is just for the sake of example]

Thanks.

[Edit: I sort of solved it now, but any other ideas are highly welcome. I will accept as an answer any alternative solution.

s <- "a."
res <- grep(s, c("a.b", "cac", "sss", "ca.f"), fixed = T, value = T)
res[substring(res, 1, nchar(s)) == s]

]

解决方案

If you want to match an exact string (string 1) at the beginning of the string (string 2), then just subset your string 2 to be the same length as string 1 and use ==, should be fairly fast.

这篇关于grep在固定= T在R的字符串的开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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