Skip to content

StringCases

Finds all occurrences of a substring.

$ wo 'StringCases["abcabc", "bc"]'
{bc, bc}
$ wo 'StringCases["hello", "l"]'
{l, l}
$ wo 'StringCases["hello", "x"]'
{}

A list of strings is handled string by string, so the matches of each stay together:

$ wo 'StringCases[{"aba", "cd"}, "a"]'
{{a, a}, {}}

A subject that is not a string is refused rather than coerced to its printed form:

$ wo 'StringCases[foo, "a"]'

StringCases::strse: A string or list of strings is expected at position 1 in StringCases[foo, a].
StringCases[foo, a]

The Overlaps option controls how much of the string a match may share with its neighbours. The default keeps matches disjoint, Overlaps -> True reports the preferred match at every start position, and Overlaps -> All reports every match at every start position:

$ wo 'StringCases["abcd", __]'
{abcd}
$ wo 'StringCases["abcd", __, Overlaps -> True]'
{abcd, bcd, cd, d}
$ wo 'StringCases["abcd", __, Overlaps -> All]'
{abcd, abc, ab, a, bcd, bc, b, cd, c, d}

A greedy pattern reports its longest match first at each start position, so Shortest flips the order within each group:

$ wo 'StringCases["abcd", Shortest[__], Overlaps -> All]'
{a, ab, abc, abcd, b, bc, bcd, c, cd, d}

A DatePattern matches the date fields it names, each read whole:

$ wo 'StringCases["2024-01-15", DatePattern[{"Year", "Month", "Day"}]]'
{2024-01-15}
$ wo 'StringCases["31/12/1999", DatePattern[{"Day", "Month", "Year"}]]'
{31/12/1999}

A field out of range matches nothing:

$ wo 'StringCases["2024-13-01", DatePattern[{"Year", "Month", "Day"}]]'
{}