Search code examples
rstringstrsplit

Using str_split() on a specific string containing a "." in R


I am trying to split a string into multiple bits when a specific set of characters is found. In this example "abc."

Here is my code

test <- "aa\abc.def/def\abd.abd...abc.def"
result <- str_split(test,"abc\\.")

So here my expected output is

"aa\" "def/def\abd.abd..." "def"

The output I get is:

"aa\abc.def/def\abd.abd..." "def"  

So it does seem to work at the end but does not work on the first one. I think it might be because of the "" but that still seems kinda of weird to me that the function would not consider the potential presence of a ""

Any help is welcome on this.


Solution

  • The issue you experience is with the string itself, not the split function. You should be using "\\" instead of "\" in the string.

    test = "aa\\abc.def/def\\abd.abd...abc.def"
    
    cat(test)
    # aa\abc.def/def\abd.abd...abc.def
    
    result = str_split(test,"abc\\.")
    result 
    
    # [[1]]
    # [1] "aa\\" "def/def\\abd.abd..." "def"