Split a String Only the At the First N Occurrences of a Delimiter

split string only by the first occurrence of a delimiter

Use the limit keyword.

For this kind of questions you can also efficiently use the inline documentation.. just type ?split (or any other function or type) in the console to retrieve a nice explanation of the function, their arguments and often usage examples. In this case:

help?> split
search: split splitext splitdir splitpath splitdrive rsplit splice! displaysize @specialize @nospecialize

split(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)

Split str into an array of substrings on occurrences of the delimiter(s) dlm. dlm can be any of the formats allowed by findnext's first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.

If dlm is omitted, it defaults to isspace.

The optional keyword arguments are:

• limit: the maximum size of the result. limit=0 implies no maximum (default)

• keepempty: whether empty fields should be kept in the result. Default is false without a dlm argument, true with a dlm argument.

See also rsplit.

Examples
≡≡≡≡≡≡≡≡≡≡

julia> a = "Ma.rch"
"Ma.rch"

julia> split(a,".")
2-element Array{SubString{String},1}:
"Ma"
"rch"

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Splits an HyperRectangle into two along an axis at a given location.

Splitting on first occurrence

From the docs:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s.split('mango', 1)[1]

Flutter/Dart: Split string by first occurrence

You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:

String s = "date   :   '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];

split string only on first instance of specified character

Use capturing parentheses:

'good_luck_buddy'.split(/_(.*)/s)
['good', 'luck_buddy', ''] // ignore the third element

They are defined as

If separator contains capturing parentheses, matched results are returned in the array.

So in this case we want to split at _.* (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

In this example our separator (matching _(.*)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .*) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

We use the s regex flag to make . match on newline (\n) characters as well, otherwise it would only split to the first newline.

split string only on first instance - java

string.split("=", 2);

As String.split(java.lang.String regex, int limit) explains:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

The string boo:and:foo, for example, yields the following results with these parameters:

Regex Limit    Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }

Split on first/nth occurrence of delimiter

Here is another solution using the gsubfn package and some regex-fu. To change the nth occurrence of the delimiter, you can simply swap the number that is placed inside of the range quantifier — {n}.

library(gsubfn)
x <- 'I like_to see_how_too'
strapply(x, '((?:[^_]*_){1})(.*)', c, simplify =~ sub('_$', '', x))
# [1] "I like" "to see_how_too"

If you would like the nth occurrence to be user defined, you could use the following:

n <- 2
re <- paste0('((?:[^_]*_){',n,'})(.*)')
strapply(x, re, c, simplify =~ sub('_$', '', x))
# [1] "I like_to see" "how_too"

Split a string only by first space in python

Just pass the count as second parameter to str.split function.

>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']


Related Topics



Leave a reply



Submit