【发布时间】:2013-03-05 11:49:28
【问题描述】:
我有一个字符串数据集,想要提取一个子字符串,直到并包括第一个冒号。早些时候我在这里发帖询问如何仅提取第一个冒号之后的部分: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 包。也许它可以提供帮助,但我更喜欢 base R 中的解决方案。
感谢您的任何建议。
【问题讨论】:
-
我认为您只是缺少捕获括号,
(和)- 您的表达式包括它们将是^([^:]+:) -
我认为您正在寻找的是正则表达式组。也许这对stackoverflow.com/questions/952275/regex-group-capture-in-r 有帮助?
标签: regex string r regex-negation