Wolfram Research

Function Repository Resource:

StringSplitBefore

Source Notebook

Split a string before each substring matching a string pattern

Contributed by: Ian Ford (Wolfram Research)

ResourceFunction["StringSplitBefore"]["string"]

splits "string" into a list of substrings before each whitespace.

ResourceFunction["StringSplitBefore"]["string",patt]

splits "string" into substrings before delimiters matching the string expression patt.

ResourceFunction["StringSplitBefore"]["string",{p1,p2,}]

splits "string" before any of the pi.

ResourceFunction["StringSplitBefore"]["string",pattval]

replaces each delimiter matching patt with val.

ResourceFunction["StringSplitBefore"]["string",{p1v1,}]

replaces each delimiter matching pi with vi.

ResourceFunction["StringSplitBefore"][{s1,s2,},p]

gives the list of results for each of the si.

Details and Options

Unlike StringSplit, ResourceFunction["StringSplitBefore"] will not remove the delimiters—it will only split the string before each delimiter.
ResourceFunction["StringSplitBefore"][s,p] otherwise behaves like StringSplit[s,p,All].
ResourceFunction["StringSplitBefore"] takes the same options as StringSplit.

Examples

Basic Examples

Split a string before each whitespace:

In[1]:=
ResourceFunction["StringSplitBefore"]["a bbb  cccc aa   d"]
Out[1]=

Split a string before every --:

In[2]:=
ResourceFunction["StringSplitBefore"]["a--bbb---ccc--dddd", "--"]
Out[2]=

Scope

Split before every run of spaces:

In[3]:=
ResourceFunction["StringSplitBefore"]["the cat in the hat"]
Out[3]=

Use string patterns:

In[4]:=
ResourceFunction["StringSplitBefore"]["192.168.0.1", "."]
Out[4]=
In[5]:=
ResourceFunction["StringSplitBefore"]["123  2.3  4  6", WhitespaceCharacter ..]
Out[5]=
In[6]:=
ResourceFunction["StringSplitBefore"]["11a22b3", _?LetterQ]
Out[6]=

Regular expressions:

In[7]:=
ResourceFunction[
 "StringSplitBefore"]["A tree, an apple, four pears. And more: two \
sacks", RegularExpression["\\W+"]]
Out[7]=

Mix regular expressions and string patterns:

In[8]:=
ResourceFunction[
 "StringSplitBefore"]["primes: 2 two 3 three 5 five ...", Whitespace ~~ RegularExpression["\\d"] ~~ Whitespace]
Out[8]=

Split into substrings before either delimiter:

In[9]:=
ResourceFunction["StringSplitBefore"]["a-b:c-d:e-f-g", {":", "-"}]
Out[9]=
In[10]:=
ResourceFunction["StringSplitBefore"]["a-b:c-d:e-f-g", ":" | "-"]
Out[10]=

Replace a delimiter:

In[11]:=
ResourceFunction["StringSplitBefore"]["a b::c d::e f g", "::" -> "--"]
Out[11]=

StringSplitBefore automatically threads over lists of strings:

In[12]:=
ResourceFunction[
 "StringSplitBefore"][{"a:b:c:d", "listable:element"}, ":"]
Out[12]=

Options

Split a string before every "c", including uppercase letters:

In[13]:=
ResourceFunction["StringSplitBefore"]["cat Cat hat CAT", "c", IgnoreCase -> True]
Out[13]=

Resource History

Related Resources

Author Notes

Author Notes

License Information