CafféSospeso
CafféSospeso

Reputation: 1178

replace random number in a string with a specific number in R

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

Answers (2)

akrun
akrun

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

data

  str1 <- str1 <- "\t<!-- number=31                                                            -->"

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

Use sub

sub("=\\d+", "=15", s)

Upvotes: 1

Related Questions