strsplit on first instance

Francis Smart picture Francis Smart · Oct 8, 2014 · Viewed 12k times · Source

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.

Answer

Rich Scriven picture Rich Scriven · Oct 8, 2014

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"