Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by a plus sign (+) character

Tags:

r

strsplit

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.

like image 235
Vasista B Avatar asked Jul 21 '15 02:07

Vasista B


People also ask

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a string with a period?

To split a string with dot, use the split() method in Java. str. split("[.]", 0);

How do you split a string with white space characters?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.


Video Answer


2 Answers

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

  • ?
  • *
  • .
  • ^
  • $
  • \
  • |
  • { }
  • [ ]
  • ( )
like image 68
Molx Avatar answered Nov 10 '22 01:11

Molx


Below Worked for me:

import re

re.split('\\+', 'ABC+CDE')

Output:

['ABC', 'CDE']

like image 26
Ravi Avatar answered Nov 10 '22 01:11

Ravi