提取特定字符 RegEx Rstudio 前面的单词

Extract word infront of certain character RegEx 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"

以 R 为基数,给定字符串 s <- "sam buy expensive toys as 125898652",您可以使用 gsub()strsplit():

> gsub(".*?as\s","",s)
[1] "125898652

> unlist(strsplit(s,split = "(?<=as\s)",perl = T))[2]
[1] "125898652"