2013-05-10 75 views
0

我從字符串中提取多種類型的模式。例如,從字符串中提取多種類型的模式

「上市2013年3月25日爲25000和銷售爲$ 10,250的2010年4月5日」

我想提取日期「2013年3月25日」,「2010年4月5日「向量」日期「和」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) 

但是訂單沒有保留。有沒有更好的方法來做到這一點?謝謝。

+0

[I已經寫了一個小函數爲這個](https://gist.github.com/klmr/5555335) - 它或多或少相同stringr函數,但它確實保持順序。 – 2013-05-10 15:52:54

+0

@KonradRudolph regmatches有什麼問題? – 2013-05-10 16:09:16

+0

@Mthethew我不知道它的事實。嘆。這會教會我正確閱讀文檔。 – 2013-05-10 16:53:47

回答

6

基礎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)) 
+1

+1:我認爲這個世界確實需要'regmatches(x,gregexpr(。))'範例的更多可行的例子。 – 2013-05-10 17:21:23

+0

它工作得很好,我學到了更多。感謝你們! – Autumn 2013-05-10 17:36:02

+0

當號碼後面有一個逗號(比如100,000美元)時,需要逗號,我如何才能提取$ 100,000?謝謝 – Autumn 2013-05-10 21:06:28