简体   繁体   English

R:在特定单词后提取数字

[英]R: Extract a number after a specific word

I have a column like below:我有一个像下面这样的专栏:

C1
we-23 pcs,qw-4 pcs
we-30 pcs
er-21 pcs,we-2 pcs
tr-23 pcs
we-0 pcs, re-2 pcs
we-0 pcs
NA

I want to extract the quantities of "we" in numeric format, with NAs preserved and no character(0).我想以数字格式提取“我们”的数量,保留 NA,没有字符(0)。 I used:我用了:

C2 <- as.numeric(str_extract_all(str_extract_all(C1, "we-*\\d+"), "\\d+"))

Result:结果:

C2
23
30
2
0
0
0
NA

However, I want to get the tr-23 pcs entry to be different than we-0 pcs.但是,我想让 tr-23 pcs 条目与 we-0 pcs 不同。 So I am using another logical column to find "we" in C1.所以我使用另一个逻辑列在 C1 中找到“我们”。 Is there a better way to do this?有没有更好的方法来做到这一点?

You may use您可以使用

C2 <- as.numeric(str_extract(C1, "(?<=we-)\\d+"))

See the regex demo .请参阅正则表达式演示

Pattern details :图案详情

  • (?<=we-) - a positive lookahead that matches a position that is preceded with we- (?<=we-) - 与前面有we-的位置匹配的正向前瞻
  • \\d+ - 1+ digits. \\d+ - 1+ 位数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM