2013-03-16 23 views
1

我有一個數據集的字符串,並希望提取一個子字符串直至幷包括第一個冒號。早些時候我在這裏發佈了問如何提取第一個冒號後面的部分:Split strings at the first colon下面我列出了一些解決當前問題的嘗試。通過第一個冒號提取字符串

我知道^[^:]+:匹配我想保留的部分,但我無法弄清楚如何提取該部分。

以下是一個示例數據集和所需結果。

my.data <- "here is: some text 
here is some more. 
even: more text 
still more text 
this text keeps: going." 

my.data2 <- readLines(textConnection(my.data)) 

desired.result <- "here is: 
0 
even: 
0 
this text keeps:" 

desired.result2 <- readLines(textConnection(desired.result)) 

# Here are some of my attempts 

# discards line 2 and 4 but does not extract portion from lines 1,3, and 5. 
ifelse(my.data2 == gsub("^[^:]+:", "", my.data2), '', my.data2) 

# returns the portion I do not want rather than the portion I do want 
sub("^[^:]+:", "\\1", my.data2, perl=TRUE) 

# returns an entire line if it contains a colon 
grep("^[^:]+:", my.data2, value=TRUE) 

# identifies which rows contain a match 
regexpr("^[^:]+:", my.data2) 

# my attempt at anchoring the right end instead of the left end 
regexpr("[^:]+:$", my.data2) 

此前面的問題涉及返回匹配的相反部分。我還沒有想出如何在R中實現這個解決方案,如果我從上面鏈接的問題的解決方案開始:Regular Expression Opposite

我最近獲得了RegexBuddy來學習正則表達式。這就是我知道^[^:]+:匹配我想要的。我只是無法使用這些信息來提取匹配。

我知道stringr包。也許它可以幫助,但我更喜歡基地R的解決方案。

謝謝你的任何意見。

+2

我認爲你只是缺少捕獲括號,'('和')' - 你的表達,包括他們將是'^([^:] +: )' – CBroe 2013-03-16 21:24:01

+0

我認爲你正在尋找的是正則表達式組。 也許這有助於http://stackoverflow.com/questions/952275/regex-group-capture-in-r? – ffledgling 2013-03-16 21:24:11

回答

6

「我知道^ [^:] +:匹配我想要保留的部分,但我無法弄清楚如何提取那部分。」

所以只是包裝圍繞括號並添加「+ $」至年底,並使用子與參考

sub("(^[^:]+:).+$", "\\1", vec) 

step1 <- sub("^([^:]+:).+$", "\\1", my.data2) 
step2 <- ifelse(grepl(":", step1), step1, 0) 
step2 
#[1] "here is:"   "0"    "even:"   "0"    
#[5] "this text keeps:" 

目前尚不清楚是否希望那些爲讓他們獨立矢量元素

> step3 <- paste0(step2, collapse="\n") 
> step3 
[1] "here is:\n0\neven:\n0\nthis text keeps:" 
> cat(step3) 
here is: 
0 
even: 
0 
this text keeps: 
4

這似乎產生你在找什麼(雖然它返回在他們冒號線的只有位):

grep(":",gsub("(^[^:]+:).*$","\\1",my.data2),value=TRUE) 
[1] "here is:"   "even:"   "this text keeps:" 
與換行符粘貼在一起

當我打字時,我看到@Dinin的回答也提出了parens,並且有ifelse,它也會給你「0」。

2

strsplit另一個不那麼優雅的方法:

x <- strsplit(my.data2, ":") 
lens <- sapply(x, length) 
y <- sapply(x, "[", 1) 
y[lens==1] <- "0" 
+0

儘可能避免正則表達式,不是不雅。 – 2013-03-17 01:19:56

相關問題