问题
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.
回答1:
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"
回答2:
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)
回答3:
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"
回答4:
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"
回答5:
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")
来源:https://stackoverflow.com/questions/26246095/strsplit-on-first-instance