Q:

R - replace part of a string using wildcards

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. 

A:

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"

A:

Could also try qdapRegex package which has a special method for such problems: rm_square
library(qdapRegex)
S1 <- "aaaaaaaaa[aaaaa]aaaa[bbbbbbb]aaaa" 
rm_square(S1, replacement = "[x]")
## [1] "aaaaaaaaa[x]aaaa[x]aaaa"

Will work the same for empty brackets
S1 <- "aaaaaaaaa[]aaaa[bbbbbbb]aaaa" 
rm_square(S1, replacement = "[x]")
## [1] "aaaaaaaaa[x]aaaa[x]aaaa"

A:

Use positive lookahead and lookbehind assertions like below.
"(?<=\\[)[^\\[\\]]*(?=\\])"

Then replace the matched characters with x
> S1<-'aaaaaaaaa[aaaaa]aaaa[bbbbbbb]aaaa'
> gsub("(?<=\\[)[^\\[\\]]*(?=\\])", "x", S1, perl=TRUE)
[1] "aaaaaaaaa[x]aaaa[x]aaaa"

Explanation:

(?<=\\[) Positive lookbehind asserts that the string you want to match must be preceded by [ symbol.
[^\\[\\]]* Matches any character but not of [ or ] zero or more times.
(?=\\]) Positive lookahead asserts that the match must be followed by ] symbol.

