在特定字符串后提取数字 [英] extract number after specific string

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

问题描述

我需要找到字符串Count of"之后的数字.Count of"字符串和数字之间可能有一个空格或一个符号.我有一些可以在 www.regex101.com 上运行但不适用于 stringr str_extract 函数的东西.

I need to find the number after the string "Count of". There could be a space or a symbol between the "Count of" string and the number. I have something that works on www.regex101.com but does not work with stringr str_extract function.

library(stringr)

shopping_list <- c("apples x4", "bag of flour", "bag of sugar", "milk x2", "monkey coconut 3oz count of 5", "monkey coconut count of 50", "chicken Count Of-10")
str_extract(shopping_list, "count of ([\\d]+)")
[1] NA NA NA NA "count of 5" "count of 50" NA

我想得到什么:

[1] NA NA NA NA "5" "50" "10"

推荐答案

str_extract(shopping_list, "(?i)(?<=count of\\D)\\d+")
# [1] NA   NA   NA   NA   "5"  "50" "10"

其中 (?i) 使模式不区分大小写,\\D 表示不是数字,而 ?<= 是一个积极回顾.

where (?i) makes the pattern case insensitive, \\D means not a number, and ?<= is a positive lookbehind.

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

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