当我尝试获取R中的数字部分时,我遇到了一个问题。例如,原始字符串是"buy 1000 shares of Google at 1100 GBP"
我需要分别提取股票数量(1000
)和价格(1100
)。此外,我需要提取股票的编号,它总是出现在"shares of"
之后。
我知道sub
和gsub
可以替换字符串,但是我应该使用什么命令来提取字符串的一部分呢?
发布于 2014-03-12 02:55:43
1)此命令按顺序提取所有数字:
s <- "buy 1000 shares of Google at 1100 GBP"
library(gsubfn)
strapplyc(s, "[0-9.]+", simplify = as.numeric)
给予:
[1] 1000 1100
2)如果数字可以是任意顺序,但如果股票数量后面总是跟着单词" shares“,价格后面总是跟着英镑,那么:
strapplyc(s, "(\\d+) shares", simplify = as.numeric) # 1000
strapplyc(s, "([0-9.]+) GBP", simplify = as.numeric) # 1100
返回与括号内的正则表达式部分匹配的字符串部分。
3)如果字符串的形式是已知的:在Z GBP时Y的X份额,则可以像这样提取X、Y和Z:
strapplyc(s, "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = c)
添加了修改过的图案,以允许数字或点。还添加了上面的(3)和以下内容:
strapply(c(s, s), "[0-9.]+", as.numeric)
strapply(c(s, s), "[0-9.]+", as.numeric, simplify = rbind) # if ea has same no of matches
strapply(c(s, s), "(\\d+) shares", as.numeric, simplify = c)
strapply(c(s, s), "([0-9.]+) GBP", as.numeric, simplify = c)
strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP")
strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = rbind)
发布于 2014-03-12 03:16:39
您可以使用sub
函数:
s <- "buy 1000 shares of Google at 1100 GBP"
# the number of shares
sub(".* (\\d+) shares.*", "\\1", s)
# [1] "1000"
# the stock
sub(".*shares of (\\w+) .*", "\\1", s)
# [1] "Google"
# the price
sub(".* at (\\d+) .*", "\\1", s)
# [1] "1100"
您还可以使用gregexpr
和regmatches
一次提取所有子字符串:
regmatches(s, gregexpr("\\d+(?= shares)|(?<=shares of )\\w+|(?<= at )\\d+",
s, perl = TRUE))
# [[1]]
# [1] "1000" "Google" "1100"
发布于 2014-03-12 03:56:27
我觉得有必要把强制性的stringr
解决方案也包括进来。
library(stringr)
s <- "buy 1000 shares of Google at 1100 GBP"
str_match(s, "([0-9]+) shares")[2]
[1] "1000"
str_match(s, "([0-9]+) GBP")[2]
[1] "1100"
https://stackoverflow.com/questions/22334028
复制相似问题