仅当字符串具有一定数量的字符时,才将字符放置在字符串中的特定位置

问题描述 投票:0回答:1

我的字符串结构如下:

vector <- c("CBR0", "CBR1", "CBR2", "CBR3", "CBR4", "CBR5", "CBR10", "CBR11")

我想在“CBR”后面插入一个零,仅表示 CBR 数字 0-9。 CBR 编号 >= 10 不需要更改。得到的向量将如下所示:

vector <- c("CBR00", "CBR01", "CBR02", "CBR03", "CBR04", "CBR05", "CBR10", "CBR11")

我可以使用

stringr
来做到这一点吗?

提前感谢您的帮助。

r regex stringr
1个回答
0
投票

使用

str_replace

library(stringr)

str_replace(vector, "CBR(\\d)$", "CBR0\\1")
[1] "CBR00" "CBR01" "CBR02" "CBR03" "CBR04" "CBR05" "CBR10" "CBR11"
© www.soinside.com 2019 - 2024. All rights reserved.