Reputation: 1178
I have a txt file and I want to replace a random number from a string with a specific number that I have choosen. For example:
txt[15] = "\t<!-- number=31 -->"
I want substitute the number after "=" with "15", but keeping all the structure and the spaces in the string. So, just changing the number. I'm trying to do it in R.
Upvotes: 1
Views: 137
Reputation: 886968
You can try with sub
sub('\\d+', '15', str1)
#[1] "\t<!-- number=15 -->"
To be exact
sub('(?<=[=])\\d+', '15', str1, perl=TRUE)
#[1] "\t<!-- number=15 -->"
Or
sub('([^=]+=)\\d+', '\\115', str1)
#[1] "\t<!-- number=15 -->"
str1 <- str1 <- "\t<!-- number=31 -->"
Upvotes: 2