从字符串中提取多种类型的模式

时间:2013-05-10 15:46:02

标签: r

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

“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)

但订单没有保留。有没有更好的方法呢?感谢。

1 个答案:

答案 0 :(得分: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))