Split a string by a plus sign (+) character

Vasista B picture Vasista B · Jul 21, 2015 · Viewed 7.2k times · Source

I have a string in a data frame as: "(1)+(2)"

I want to split with delimiter "+" such that I get one element as (1) and other as (2), hence preserving the parentheses. I used strsplit but it does not preserve the parenthesis.

Answer

Molx picture Molx · Jul 21, 2015

Use

strsplit("(1)+(2)", "\\+")

or

strsplit("(1)+(2)", "+", fixed = TRUE)

The idea of using strsplit("(1)+(2)", "+") doesn't work since unless specified otherwise, the split argument is a regular expression, and the + character is special in regex. Other characters that also need extra care are

  • ?
  • *
  • .
  • ^
  • $
  • \
  • |
  • { }
  • [ ]
  • ( )