r - 提取某些字符正则表达式 Rstudio 前面的单词
问题描述
我有这个词,"sam buy expensive toys as 125898652"
。我想提取“as”之后的单词,即“125898652”。
我在用着
(?<=as\s)+[^\s]+
我已经在https://regex101.com/r/NaWAl1/1上试过了,效果很好。当我在 R 上执行它时,它返回错误为
Error: '\s' is an unrecognized escape in character string starting ""(?<='as'\s"
所以我将其修改为
(?<='CR'\s)+[^\s]+
它返回不同的错误:
Error in stri_extract_first_regex(string, pattern, opts_regex = opts(pattern)) :
Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX)
有人可以向我解释为什么 R 中的正则表达式不同以及如何使其工作。太感谢了
解决方案
使用sub
sub(".*as\\s(\\w+).*", "\\1", "sam buy expensive toys as 125898652")
#[1] "125898652"
或向后看正则表达式
stringr::str_extract("sam buy expensive toys as 125898652", "(?<=as\\s)\\w+")
#[1] "125898652"
对于其中包含,
并且可能有小数位的单词,我们可以做
x <- "sam buy expensive toys as 128984,45697.00"
sub(".*as\\s(\\d+\\.?\\d+).*", "\\1",gsub(',', '', x))
#[1] "12898445697.00"
推荐阅读
- php - 如何阅读此日期时间格式 2019-12-17T17:23:49.782Z?
- python-3.x - 确保统一功能签名的最佳方法
- c++ - 如何从 wav 文件中获取采样率?
- javascript - 动态检查是否使用 Jquery 检查了单选按钮
- reactjs - 如何在 React 中使用 wavesurfer.js?
- r - 样品在 sapply 中抽取,无需更换
- uitableview - swift4 uitableview 保留选择
- amazon-web-services - eks http https 使用入口重定向
- python - pytest:将测试标记为“必须通过”,如果失败则停止测试
- google-app-engine - 如何将 Google Cloud OCR 计算限制在一个区域内