基于分隔符从字符串中提取数字 [英] Extracting numbers from character string based on delimiters

查看:68
本文介绍了基于分隔符从字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

a <- seq(1:5)
b <- c("abc_a_123456_defghij_1", "abc_a_78912_abc_2", "abc_a_345678912_xyzabc_3",
                          "abc_b_34567_defgh_4", "abc_c_891234556778_ijklmnop_5")
df <- data.frame(a, b)
df$b <- as.character(df$b)

我需要提取 df$b 中第二个和第三个下划线之间的数字并分配给 df$c.

And I need to extract the numbers in df$b that come between the second and third underscores and assign to df$c.

我猜有一个相当简单的解决方案,但还没有找到.实际数据集相当大(3MM 行),因此效率是一个因素.

I'm guessing there's a fairly simple solution, but haven't found it yet. The actual dataset is fairly large (3MM rows) so efficiency is a bit of a factor.

感谢您的帮助!

推荐答案

我们可以使用 sub 来匹配 zeor 或多个不是 _ 的字符([^_]*) 从字符串的开头 (^) 开始,后跟一个下划线 (_),然后是另一组不是下划线后跟下划线,捕获组中的多个数字之一 ((\\d+)) 后跟下划线和其他字符,然后将其替换为该组的反向引用,最后转换将其转换为 numeric

We can use sub to match the zeor or more characters that are not a _ ([^_]*) from the start (^) of the string followed by an underscore (_), then another set of characters that are not an underscore followed by underscore, capture the one of more numbers that follows in a group ((\\d+)) followed by underscore and other characters, then replace it with the backreference for that group and finally convert it to numeric

as.numeric(sub("^[^_]*_[^_]+_(\\d+)_.*", "\\1", df$b))
#[1]       123456        78912    345678912        34567 891234556778

这篇关于基于分隔符从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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