替换 R 中第一次出现的“:”但不是第二次

Posted

技术标签:

【中文标题】替换 R 中第一次出现的“:”但不是第二次【英文标题】:Replace first occurrence of ":" but not second in R 【发布时间】:2016-03-20 01:51:24 【问题描述】:

为了能够处理,我想替换字符串中第一次出现的:(这是我的标记,演讲开始)。

text <- c("Mr. Mark Francois (Rayleigh) (Con): If the scheme was so poorly targeted, why were the Government about to roll it out to employees in the Department of Trade and Industry and the Department for Work and Pensions on the very day the Treasury scrapped it? The CBI and the TUC have endorsed the scheme, which has helped 500,000 people and their families to improve their computer skills. When the Chancellor announced the original concession, he told the  Daily Record:", "Even at this eleventh hour, will the Government recognise that this is a poor decision, taken by an analogue Chancellor who is stuck in the past and reversing?", "Dawn Primarolo: The hon. Gentleman answers his own question, as the US does not have similar schemes. He is right to address the question of how we give people in the greatest need access to computer technology, but the Low Pay Commission\u0092s 2005 report showed that that was not happening under the scheme. Why should the Government spend £200 million on a poorly targeted scheme? It was being abused and was not delivering, so the Government have refocused to ensure that the objective is achieved.")

我能够找到第一个 : 使用的位置

lapply(gregexpr("\\:", text), head, 1)

[[1]]
[1] 35

[[2]]
[1] -1

[[3]]
[1] 15

但是,我无法在 text 中替换它(例如,使用 |)。

【问题讨论】:

【参考方案1】:

我们可以使用sub,因为它只匹配第一次出现的模式:,然后我们将其替换为|

sub(':', '|', text)

【讨论】:

@Thomas sub 只替换第一次出现的:。我想这就是您在问题中提出的问题。 这正是sub()gsub()之间的区别。【参考方案2】:

您也可以使用来自stringr 包的str_replace

text1 <- c("ABC:DEF:", "SDF", "::ASW")
library(stringr)
str_replace(text1, ":", "|")
# [1] "ABC|DEF:" "SDF"      "|:ASW"  

这会将第一次出现的: 替换为|

【讨论】:

以上是关于替换 R 中第一次出现的“:”但不是第二次的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 匹配第一次出现的字符串以进行 gsub 替换

如何替换字符串中所有但第一次出现的模式

用R中的另一个值替换数据框多列中出现的数字

正则表达式替换换行符,如果它们出现超过一次,包括中间有空格的组合

关于高德地图Android开发时地图只显示一次第二次打开不定位的解决办法

替换字符串中最后一次出现的字符串