0

Having a simplified example string that looks like this one:

string = "AA: 1%, BB: 2%, CC: 3%, DD: 4% and EE: 5%."

I would like to replace a part of it by matching from a pattern. I tried using gsub this way:

gsub("(BB{1}.*%{1}), ","BB: no data, ",string)

but it returns the next:

"AA: 1%, BB: no data, DD: 4% and EE: 5%."

As if it is looking for the % simbol from the end. I would like to substitute until the next %, not the last, keeping the CC part. The desired output:

"AA: 1%, BB: no data, CC: 3%, DD: 4% and EE: 5%."

This kind of questions often are marked as duplicate. I've been searching for half hour and nothing, so I decided to ask if some regexp masters may help.

lmo
  • 37,904
  • 9
  • 56
  • 69
Alx_Roth
  • 13
  • 5

1 Answers1

0

How about just:

gsub("(BB: )\\d%","\\1no data", string)
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • thank you to both of you!! both works but I remain one doubt. In my trying and in the PKumar example, if you remove the () actually it doesn't change the output. I wanted to change what is in the parenthesis, similar as andrew does, but it changes the whole pattern, not only the parenthesis. Is there a way to change what is in the parenthesis? – Alx_Roth May 28 '18 at 16:20
  • In the example you give in your post, the only thing you're actually changing is the `2%` after `BB`, to `no data`. Can you provide an example of what you're describing in this comment? It sounds like you want to replace matched groups - but it would be helpful if you can give an example and desired output that fits this problem. – andrew_reece May 28 '18 at 16:27
  • yeah thats what I wanted. You pointed the right direction, I found usefull info at this [question](https://stackoverflow.com/questions/952275/regex-group-capture-in-r-with-multiple-capture-groups) by using `stringr::str_match`. But anyway, in this case the solution that you provided did the trick for me. Thank you so much!! I will give you +1 when my reputation lets me :) – Alx_Roth May 28 '18 at 20:31
  • You're welcome! And good that you found `stringr`, it's a great package. If you have an alternate solution that you think would contribute to your post, please add it - others might find it useful. – andrew_reece May 28 '18 at 20:37