R - replace part of a string using wildcards

r, regex

Solution

A simple regex would be like

\\[.+?\\]

Example http://regex101.com/r/xE1rL1/1

Example Usage

s1 <- 'aaaaaaaaa[aaaaa]aaaa[bbbbbbb]aaaa'
gsub("\\[.+?\\]", "[x]", s1)
## [1] "aaaaaaaaa[x]aaaa[x]aaaa"

Regular expression

`\\[` matches opening `[`

`.+?` non greedy matching of anything

`\\]` matches closing `]`

EDIT

For safety, if nothing is present in the the `[]`, then the regex can be slightly modified as

s1 <- 'aaaaaaaaa[]aaaa[bbbbbbb]aaaa'
gsub("\\[.*?\\]", "[x]", s1)
##[1] "aaaaaaaaa[x]aaaa[x]aaaa"

Problem

I just started using R again, and I was wondering is there a way to replace part of a string using wildcards. For example: say I have ``` S1 <- "aaaaaaaaa[aaaaa]aaaa[bbbbbbb]aaaa" ``` and I want to replace everything within square brackets with 'x', such that the new string is ``` "aaaaaaaaa[x]aaaa[x]aaaa" ``` Is this possible to do in R? Please note what is in the square bracket can be of variable length.

Original source