0

I'm trying to remove [ and ] characters from a string in R, I have tried the following code:

gsub("[]", "", p1)

but this doesn't work.

md1630
  • 841
  • 1
  • 10
  • 28
  • Try this: `gsub("[\\]\\[]", "", p1)`. The first argument of `gsub()` is a regular expression and the left and right brackets are special characters that denote a class of characters, and `"[]"`,matches nothing. I updated the regex string accoring to @BondedDust's comment – Jthorpe May 09 '15 at 20:58
  • 2
    Read up on character classes in ?regex where this is specifically addressed: `gsub("[][]", "", "yy][]oo]") [1] "yyoo"`. I'm not getting success with Jthorpe's solution but am with this pattern: `"\\]|\\["` – IRTFM May 09 '15 at 20:58
  • My original regex sting (`'}{ – Jthorpe May 09 '15 at 21:04
  • My original regex string (`"]["`) matched a `]` followed by a '[', which obviously wasn't correct...this pattern `"[][]]"` is an expression class with two members ( `[` and `]`) and '\\\[|\\\]' matches `[` or `]`. Note the double escape characters -- one to escape the \ in the R string, the other to escape the `[` in the regular expression. – Jthorpe May 09 '15 at 21:10
  • As per BondedDust's comment above, his first example is only briefly mentioned in the `?regex` documentation, but in using character classes it works because in order to include a `]` in a character class it must appear first in the list. `gsub("[][]", "", p1)` is the solution I prefer. – Forrest R. Stevens May 09 '15 at 21:12

2 Answers2

3

It doesn't work because [] indicates an invalid character class in which it should throw an error saying "invalid regular expression", you need to put together a complete character class.

gsub('[][]', '', p1)

I would recommend reading up on Character Classes or Character Sets ...

hwnd
  • 69,796
  • 4
  • 95
  • 132
2

You can try:

x = 'mycharac[ter]'
gsub('\\[|\\]','',x)
#[1] "mycharacter"
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87