Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strsplit on first instance [duplicate]

Tags:

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.

like image 438
Francis Smart Avatar asked Oct 07 '14 22:10

Francis Smart


People also ask

How do you split a string only on the first instance of specified character?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split a string at first instance of a character in python?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How to use strsplit in matlab?

C = strsplit( str , delimiter ) splits str at the delimiters specified by delimiter . If str has consecutive delimiters, with no other characters between them, then strsplit treats them as one delimiter. For example, both strsplit('Hello,world',',') and strsplit('Hello,,,world',',') return the same output.

What is Maxsplit in Python?

maxsplit : It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then the default is -1 that means there is no limit. Returns : Returns a list of strings after breaking the given string by the specified separator.


2 Answers

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" 
like image 52
Rich Scriven Avatar answered Oct 07 '22 19:10

Rich Scriven


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) 
like image 28
Henrik Avatar answered Oct 07 '22 20:10

Henrik