R: str_split_fixed 是否可以按各种字符拆分?
R: Is it possible to split according to various characters with str_split_fixed?
我有一个字符串,我想将其分成不同的部分。
test = c("3 CH • P" ,"9 CH • P" , "2 CH • P" , "2 CH, 5 ECH • V",
"3 ECH • V", "4 ECH • P" )
我知道使用 stringr()
中的 str_split_fixed()
我可以根据某个字符拆分字符串。例如:
test.1 = str_split_fixed(test, c("•"), 2)
> test.1
[,1] [,2]
[1,] "3 CH " " P"
[2,] "9 CH " " P"
[3,] "2 CH " " P"
[4,] "2 CH, 5 ECH " " V"
[5,] "3 ECH " " V"
[6,] "4 ECH " " P"
但是,我想知道是否可以设置多个字符(例如"•"
和","
)来拆分字符串?
您可以尝试使用 gsub
来摆脱 •
的:
test <- c("3 CH • P" ,"9 CH • P" ,
"2 CH • P" , "2 CH, 5 ECH • V",
"3 ECH • V", "4 ECH • P" )
test_sub <- gsub("•", ",", test)
str_split_fixed(test_sub, "[, ]+", n = 5)
#or, use this version with an unfixed length:
strsplit(test_sub, "[, ]+")
This thread 关于字符串拆分可能有用也可能没用。
我有一个字符串,我想将其分成不同的部分。
test = c("3 CH • P" ,"9 CH • P" , "2 CH • P" , "2 CH, 5 ECH • V",
"3 ECH • V", "4 ECH • P" )
我知道使用 stringr()
中的 str_split_fixed()
我可以根据某个字符拆分字符串。例如:
test.1 = str_split_fixed(test, c("•"), 2)
> test.1
[,1] [,2]
[1,] "3 CH " " P"
[2,] "9 CH " " P"
[3,] "2 CH " " P"
[4,] "2 CH, 5 ECH " " V"
[5,] "3 ECH " " V"
[6,] "4 ECH " " P"
但是,我想知道是否可以设置多个字符(例如"•"
和","
)来拆分字符串?
您可以尝试使用 gsub
来摆脱 •
的:
test <- c("3 CH • P" ,"9 CH • P" ,
"2 CH • P" , "2 CH, 5 ECH • V",
"3 ECH • V", "4 ECH • P" )
test_sub <- gsub("•", ",", test)
str_split_fixed(test_sub, "[, ]+", n = 5)
#or, use this version with an unfixed length:
strsplit(test_sub, "[, ]+")
This thread 关于字符串拆分可能有用也可能没用。