Replacing the nth number in a string

  • A+

I have a set of files which I had named incorrectly. The file name is as follows.

Generation_Flux_0_Model_200.txt Generation_Flux_101_Model_43.txt Generation_Flux_11_Model_3.txt 

I need to replace the second number (the model number) by adding 1 to the existing number. So the correct names would be

Generation_Flux_0_Model_201.txt Generation_Flux_101_Model_44.txt Generation_Flux_11_Model_4.txt 

This is the code I wrote. I would like to know how to specify the position of the number (replace second number in the string with the new number)?

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)) 

Answering the question, if you want to increment a certain number inside a string, you may use

> 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"   

nth here is the number of the digit chunk to increment.

Pattern details

  • ^((?://D*//d+){n}//D*) - Capturing group 1 (the value is accessed in the gsubfn method via x):
    • (?://D*//d+){n} - an n occurrences of
      • //D* - 0 or more chars other than digits
      • //d+ - 1+ digits
    • //D* - 0+ non-digits
  • (//d+) - Capturing group 2 (the value is accessed in the gsubfn method via y): one or more digits


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: