0

我正在从字符串中提取多种类型的模式。例如,

“2013 年 3 月 25 日以 25000 的价格上市,2010 年 4 月 5 日以 10,250 美元的价格售出”

我想将日期“03/25/2013”​​“4/5/2010”提取到向量“日期”,将“25000”“$10,250”提取到向量金额。

text <- "Listed 03/25/2013 for 25000 and sold for $10,250 on 4/5/2010"
  # extract dates
dates <- str_extract_all(text,"\\d{1,2}\\/\\d{1,2}\\/\\d{4}")[[1]]
  # extract amounts
text2 <- as.character(gsub("\\d{1,2}\\/\\d{1,2}\\/\\d{4}", " ", text))
amountsdollar <- as.character(str_extract_all(text2,"\\$\\(?[0-9,.]+\\)?"))
text3 <- as.character(gsub("\\$\\(?[0-9,.]+\\)?", " ", text2))
amountsnum <- as.character(str_extract_all(text3,"\\(?[0-9,.]+\\)?"))
amounts <- as.vector(c(amountsdollar, amountsnum))
list(dates, amounts)

但是订单没有保留。有更好的方法吗?谢谢。

4

1 回答 1

6

base R 处理得很好

x <- "Listed 03/25/2013 for 25000 and sold for $10,250, on 4/5/2010"
date.pat <- '\\d{1,2}/\\d{1,2}/\\d{2,4}'
amount.pat <- '(?<=^| )[$,0-9]+[0-9](?=,|\\.|$| )'

dates <- regmatches(x, gregexpr(date.pat, x))
amounts <- regmatches(x, gregexpr(amount.pat, x, perl=TRUE))
于 2013-05-10T16:04:17.563 回答