在两个可能的分隔符之一之前查找单词 [英] Find a word before one of two possible separators

查看:26
本文介绍了在两个可能的分隔符之一之前查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

word:12335
anotherword:2323434
totallydifferentword/455
word/32

我需要仅使用基本 R 函数来获取 :/ 之前的字符串.我可以使用 stringr 来做到这一点,但不想在我的包中添加另一个依赖项.单词可以有可变数量的字符,但总是以分隔符(之一)结尾.我不需要保留后面的内容.

I need to grab the character string before the : or / using only base R functions. I can do this using stringr but don't want to add another dependency to my package. The words can have variable number of character but would always end at (one of) the separator(s). I don't need to keep what comes after.

推荐答案

也许试试:

x <- c("word:12335", "anotherword:2323434", "totallydifferentword/455", "word/32")
lapply(strsplit(x, ":|/"), function(z) z[[1]]) #as a list
sapply(strsplit(x, ":|/"), function(z) z[[1]]) #as a string

gsub 有一些正则表达式解决方案也可以使用,但根据我遇到类似问题的经验,strsplit 会不那么雄辩,但速度更快.

There are regex solutions with gsub that will work too but in my experiences with similar problems strsplit will be less eloquent but faster.

我认为这个正则表达式也能正常工作:

I supose this regex would work as well:

gsub("([a-z]+)([/|:])([0-9]+)", "\\1", x)

在这种情况下 gsub 更快:

In this case gsub was faster:

Unit: microseconds
        expr    min     lq median     uq     max
1     GSUB() 19.127 21.460 22.392 23.792 106.362
2 STRSPLIT() 46.650 50.849 53.182 54.581 854.162

这篇关于在两个可能的分隔符之一之前查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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