从R中的单个字符串中提取所有数字

Ber*_*tie 17 regex r

我们假设你有一个字符串:

strLine <- "The transactions (on your account) were as follows: 0 3,000 (500) 0 2.25 (1,200)"
Run Code Online (Sandbox Code Playgroud)

是否有一个函数将数字去除到数组/向量中,产生以下所需的解决方案:

result <- c(0, 3000, -500, 0, 2.25, -1200)?
Run Code Online (Sandbox Code Playgroud)

result[3] = -500
Run Code Online (Sandbox Code Playgroud)

请注意,数字以会计形式显示,因此负数出现在()之间.此外,您可以假设只有数字出现在数字首次出现的右侧.我对regexp并不是那么好,所以如果你能提供帮助,我会很感激.此外,我不想假设字符串总是相同,所以我希望在第一个数字的位置之前删除所有单词(和任何特殊字符).

Ari*_*man 35

library(stringr)
x <- str_extract_all(strLine,"\\(?[0-9,.]+\\)?")[[1]]
> x
[1] "0"       "3,000"   "(500)"   "0"       "2.25"    "(1,200)"
Run Code Online (Sandbox Code Playgroud)

将parens改为负数:

x <- gsub("\\((.+)\\)","-\\1",x)
x
[1] "0"      "3,000"  "-500"   "0"      "2.25"   "-1,200"
Run Code Online (Sandbox Code Playgroud)

然后as.numeric()或者taRifx::destring完成了(在下一版本destring会默认支持底片所以keep选项不会是必要的):

library(taRifx)
destring( x, keep="0-9.-")
[1]    0 3000  -500    0    2.25 -1200
Run Code Online (Sandbox Code Playgroud)

要么:

as.numeric(gsub(",","",x))
[1]     0  3000  -500     0     2.25 -1200
Run Code Online (Sandbox Code Playgroud)

  • 这很可怕。你的正则表达式像我想要的那样工作。我试过,5 个正则表达式,没有一个带来独立于十进制符号 (., ,) 的值,你做的。谢谢! (2认同)

Mat*_*rde 19

为了完整起见,这是基本的R方式......

x <- unlist(regmatches(strLine, gregexpr('\\(?[0-9,.]+', strLine)))
x <- as.numeric(gsub('\\(', '-', gsub(',', '', x)))
[1]     0.00  3000.00  -500.00     0.00     2.25 -1200.00
Run Code Online (Sandbox Code Playgroud)