regex - 替换第一次出现的“:”,而不是第二个

标签 regex r lapply gsub

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

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替换它(例如,用|替换)。

最佳答案

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

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

关于regex - 替换第一次出现的“:”,而不是第二个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269466/

相关文章:

r - K-均值算法:Lloyd、Forgy、MacQueen、Hartigan-Wong

javascript - 字符串转正则表达式

python - 从url中提取uuid

R ggplot : "cross effect" in legend (not going away with show. 图例 = NA)

r - cbind 列表的第二个元素在一起

r - 使用 *apply 函数访问数据框的列名

r - 没有适用于 'separate_' 的方法应用于类 "character"的对象

Javascript - 如何知道有多少字符串与另一个字符串匹配?

javascript 分解 VIN 号码

r - 带工具提示的 Ggplotly 在使用 geom_rect() 时出现问题