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]
Is there a function to split by the FIRST instance of a delimiter in C?
The first time you call strtok
, use the delimiter you want to split with.
For the second call, use an empty delimiter string (if you really want the rest of the string) or use "\n"
, in the case that your string might include a newline character and you don't want that in the split (or even "\r\n"
):
const char* first = strtok(buf, ":");
const char* rest = strtok(NULL, "");
/* or: const char* rest = strtok(NULL, "\n"); */
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 on only first occurance of character/delimiter
If I understand correctly this will do the job; Click here for the fiddle
DECLARE @s VARCHAR(50)= 'City-Of-Style'
SELECT SUBSTRING(@s,0,CHARINDEX('-',@s,0)) AS firstPart,
SUBSTRING(@s,CHARINDEX('-',@s,0)+1,LEN(@s)) AS secondPart
Split string based on the first occurrence of the character
You can specify how many substrings to return using string.Split
:
var pieces = myString.Split(new[] { ',' }, 2);
Returns:
101
a,b,c,d
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.
split string only on first instance - java
string.split("=", limit=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" }
How to split a string by the first occurrence of the delimiter?
Use split_once
. It returns Some((before, after))
if the delimiter exists, and None
if it doesn't.
fn main() {
let s = "KEY1=value1=thing1";
match s.split_once('=') {
Some((key, value)) => {
println!("key: {}", key);
println!("value: {}", value);
}
None => {
println!("expected a key-value pair");
}
}
}
key: KEY1
value: value1=thing1
How can i split a string into two on the first occurrence of a character
str.split takes a maxsplit argument, pass 1 to only split on the first -
:
print components[i].rstrip().split('-',1)
To store the output in two variables:
In [7]: s = "console-3.45.1-0"
In [8]: a,b = s.split("-",1)
In [9]: a
Out[9]: 'console'
In [10]: b
Out[10]: '3.45.1-0'
Split string at separator after first occurrence
You can try to use regular expressions for this job.
Just note that this is an extremely specific (and, at the same time generic) regular expression based on your only sole example.
import re
_REGEX = re.compile('^(((\.\.?)?\/)*[^\/]*)((\/?(\.\.)?)*)$')
def split_path(path):
structure = _REGEX.match(path or '').groups()
return structure[0], structure[3]
Testing
>>> split_path('../../../folder.123/../..')
('../../../folder.123', '/../..')
>>> split_path('../../../folder.123')
('../../../folder.123', '')
>>> split_path('folder.123')
('folder.123', '')
>>> split_path('/')
('/', '')
>>> split_path('')
('', '')
Related Topics
Where Col1,Col2 in (...) [SQL Subquery Using Composite Primary Key]
Ora-01843 Not a Valid Month- Comparing Dates
Find SQL Table Name with a Particular Column
SQL Using If Not Null on a Concatenation
What Are the Main Differences Between Option(Optimize for Unknown) and Option(Recompile)
Multiple Foreign Keys to a Single Column
Cannot Use Group by and Over(Partition By) in the Same Query
How to Generate Crud Stored Procedures from a Table in SQL Server Management Studio
How to Create an "On-The-Fly" Mapping Table Within a Select Statement in Postgresql
Postgres "Missing From-Clause Entry" Error on Query with With Clause
SQL Server - Check to See If Cast Is Possible
Is There a Postgres Command to List/Drop All Materialized Views
Is Possible to Reuse Subqueries
Differencebetween Oracle's 'Yy' and 'Rr' Date Mask
Why Can't I Use "Create Schema" in a Begin/End Block in SQL Management Studio