首页 > 解决方案 > 提取某些字符正则表达式 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 中的正则表达式不同以及如何使其工作。太感谢了

标签: rregexstringextraction

解决方案


使用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"

推荐阅读