word:12335
anotherword:2323434
totallydifferentword/455
word/32我只需要使用base R函数在:或/之前抓取字符串。我可以使用stringr来做到这一点,但是我不想给我的包添加另一个依赖项。单词可以具有可变数量的字符,但始终以分隔符(其中之一)结束。我不需要保留之后发生的事情。
发布于 2012-10-03 00:22:50
也许可以试试:
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不会那么有说服力,但速度更快。
我假设这个正则表达式也可以工作:
gsub("([a-z]+)([/|:])([0-9]+)", "\\1", x)在这种情况下,gsub更快:
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发布于 2012-10-03 00:22:53
在Ruby http://rubular.com/r/PzVQVIpKPq中,类似这样的代码就可以了。
^(\w+)(?:[:\/])从字符串的前面开始,抓取任何单词字符并捕获它们,直到到达非捕获的/或:
发布于 2012-10-03 00:21:11
This regex seems to work。你能在R中使用它吗?
https://stackoverflow.com/questions/12694220
复制相似问题