替换字符串中的第n个数字

Sri*_*ine 6 regex r

我有一组错误命名的文件.文件名如下.

Generation_Flux_0_Model_200.txt
Generation_Flux_101_Model_43.txt
Generation_Flux_11_Model_3.txt
Run Code Online (Sandbox Code Playgroud)

我需要通过在现有数字上加1来替换第二个数字(型号).所以正确的名字就是

Generation_Flux_0_Model_201.txt
Generation_Flux_101_Model_44.txt
Generation_Flux_11_Model_4.txt
Run Code Online (Sandbox Code Playgroud)

这是我写的代码.我想知道如何指定数字的位置(用新数字替换字符串中的第二个数字)?

reNameModelNumber <- function(modelName){

  #get the current model number
  modelNumber = as.numeric(unlist(str_extract_all(modelName, "\\d+"))[2])

  #increment it by 1
  newModelNumber = modelNumber + 1

  #building the new name with gsub 
  newModelName = gsub("  regex ", newModelNumber, modelName) 

  #rename
  file.rename(modelName, newModelName)


}


reactionModels = list.files(pattern = "^Generation_Flux_\\d+_Model_\\d+.txt$")

sapply(reactionFiles, function(x) reNameModelNumber(x))
Run Code Online (Sandbox Code Playgroud)

akr*_*run 8

我们可以使用gsubfn增加1.捕获字符串的数字((\\d+))后跟. and 'txt' at the end ($`),并通过向其添加1来替换它

library(gsubfn)
gsubfn("(\\d+)\\.txt$", ~ as.numeric(x) + 1, str1)
#[1] "Generation_Flux_0_Model_201"  "Generation_Flux_101_Model_44"
#[3] "Generation_Flux_11_Model_4"  
Run Code Online (Sandbox Code Playgroud)

数据

str1 <- c("Generation_Flux_0_Model_200.txt", "Generation_Flux_101_Model_43.txt", 
                   "Generation_Flux_11_Model_3.txt")
Run Code Online (Sandbox Code Playgroud)


Wik*_*żew 6

回答这个问题,如果你想在字符串中增加一定数量,你可以使用

> library(gsubfn)
> nth = 2
> reactionFiles <- c("Generation_Flux_0_Model_200.txt", "Generation_Flux_101_Model_43.txt", "Generation_Flux_11_Model_3.txt")
> gsubfn(paste0("^((?:\\D*\\d+){", nth-1, "}\\D*)(\\d+)"), function(x,y,z) paste0(x, as.numeric(y) + 1), reactionFiles)
[1] "Generation_Flux_0_Model_201.txt"  "Generation_Flux_101_Model_44.txt" "Generation_Flux_11_Model_4.txt"  
Run Code Online (Sandbox Code Playgroud)

nth 这是要增加的数字块的编号.

图案细节

  • ^((?:\\D*\\d+){n}\\D*)- 捕获组1(gsubfn通过方法访问该值x):
    • (?:\\D*\\d+){n}- n次出现
      • \\D* - 除数字以外的0个或更多字符
      • \\d+ - 1+位数
    • \\D* - 0+非数字
  • (\\d+)- 捕获组2(gsubfn通过方法访问该值y):一个或多个数字