[英]replace element of string 3 - 10 positions after a pattern
理想情況下,在基礎 R 中,我需要某種字符串操作來檢測模式並在模式之后更改字符串 3 個位置。
example <- "when string says SOMETHING = #c792ea"
所需的 output:
當字符串說 SOMETHING = #001628
我已經嘗試過 gsub 但我不確定如何讓它在模式之后替換字符。
如果它基於字符的 position,那么我們可以使用substring
賦值
substring(example, 30) <- "#001628"
example
#[1] "when string says SOMETHING = #001628"
或者如果我們需要找到以#
開頭的單詞的position
library(stringr)
posvec <- c(str_locate(example, "#\\w+"))
substring(example, posvec[1], posvec[2]) <- "#001628"
# // or with
# str_sub(example, posvec[1], posvec[2]) <- "#001628"
另一種選擇是在=
和一個或多個空格( \\s*
)之后更改sub
sub("=\\s*.*", "= #001628", example)
#[1] "when string says SOMETHING = #001628"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.