我有一個數據集的字符串,並希望提取一個子字符串直至幷包括第一個冒號。早些時候我在這裏發佈了問如何提取第一個冒號後面的部分: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的解決方案。
謝謝你的任何意見。
我認爲你只是缺少捕獲括號,'('和')' - 你的表達,包括他們將是'^([^:] +: )' – CBroe 2013-03-16 21:24:01
我認爲你正在尋找的是正則表達式組。 也許這有助於http://stackoverflow.com/questions/952275/regex-group-capture-in-r? – ffledgling 2013-03-16 21:24:11