24

I would like to write a strsplit command that grabs the first ")" and splits the string.

For example:

f("12)34)56")
"12" "34)56"

I have read over several other related regex SO questions but I am afraid I am not able to make heads or tails of this. Thank you any assistance.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Francis Smart
  • 3,875
  • 6
  • 32
  • 58

5 Answers5

22

You could get the same list-type result as you would with strsplit if you used regexpr to get the first match, and then the inverted result of regmatches.

x <- "12)34)56"
regmatches(x, regexpr(")", x), invert = TRUE)
# [[1]]
# [1] "12"    "34)56"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
11

Need speed? Then go for stringi functions. See timings e.g. here.

library(stringi)
x <- "12)34)56"
stri_split_fixed(str = x, pattern = ")", n = 2)
Community
  • 1
  • 1
Henrik
  • 65,555
  • 14
  • 143
  • 159
6

It might be safer to identify where the character is and then substring either side of it:

x <- "12)34)56"
spl <- regexpr(")",x)
substring(x,c(1,spl+1),c(spl-1,nchar(x)))
#[1] "12"    "34)56"
thelatemail
  • 91,185
  • 12
  • 128
  • 188
5

Another option is to use str_split in the package stringr:

library(stringr)
f <- function(string)
{
  unlist(str_split(string,"\\)",n=2))
}
> f("12)34)56")
[1] "12"    "34)56"
nrussell
  • 18,382
  • 4
  • 47
  • 60
3

Replace the first ( with the non-printing character "\01" and then strsplit on that. You can use any character you like in place of "\01" as long as it does not appear.

strsplit(sub(")", "\01", "12)34)56"), "\01")
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks to the suggestion but this is dangerous because in general there might be a comma before the `)` such as `strsplit(sub(")", ",", ",12)34)56"), ",")`. – Francis Smart Oct 08 '14 at 06:52