Skip to content
AgileLogics
7 min read

String Patterns and Text

Prerequisites: Patterns

String functions accept string patterns, built with ~~ (StringExpression) and named character classes — or regular expressions.

Symbolic string patterns

StringCases["a1b22c333", DigitCharacter ..]
StringMatchQ["abc123", LetterCharacter .. ~~ DigitCharacter ..]
StringSplit["a1b2c3", DigitCharacter]
StringCases["<b>x</b><b>y</b>", "<b>" ~~ Shortest[s__] ~~ "</b>" :> s]
{1, 22, 333}
True
{a, b, c}
{x, y}
Pattern Matches
DigitCharacter, LetterCharacter, WhitespaceCharacter one character of that kind
p .. one or more repetitions of p
a ~~ b a followed by b
x__ one or more characters, named x
Shortest[p] the shortest match instead of the longest
StartOfString, EndOfString, WordBoundary positions

The results {1, 22, 333} above are strings ("1", "22", "333") — use ToExpression or FromDigits to turn them into numbers.

Rearranging with named parts

StringReplace["2024-03-15",
  y : DigitCharacter .. ~~ "-" ~~ m : DigitCharacter .. ~~ "-" ~~ d : DigitCharacter .. :>
    d <> "/" <> m <> "/" <> y]
15/03/2024

Regular expressions

RegularExpression["..."] uses standard (PCRE) syntax. Backslashes must be doubled inside Wolfram Language strings:

StringCases["x=1, y=22", RegularExpression["\\d+"]]
StringReplace["2024-03-15", RegularExpression["(\\d+)-(\\d+)-(\\d+)"] -> "$3/$2/$1"]
StringCases["mail user@example.com or admin@test.org",
  RegularExpression["\\w+@\\w+\\.\\w+"]]
{1, 22}
15/03/2024
{user@example.com, admin@test.org}

$1, $2, ... refer to captured groups. Try your regular expressions in the Regex Tester first — then double the backslashes.

Working with text

words = TextWords["The cat and the hat sat."]
Counts[ToLowerCase[words]]
StringTemplate["Hello, `name`! You are `age`."][<|"name" -> "Ada", "age" -> 36|>]
{The, cat, and, the, hat, sat}
<|the -> 2, cat -> 1, and -> 1, hat -> 1, sat -> 1|>
Hello, Ada! You are 36.
  • TextWords splits text into words, dropping punctuation; TextSentences splits it into sentences.
  • StringTemplate fills named slots from an association.
  • Built-in natural-language functions go further: WordCloud, TextStructure, Interpreter["Date"], and more.

Practice

Extract every number (including decimals) from "Total: 12.5 kg, 3 boxes, 0.75 m" and add them up.

Show solution
nums = StringCases["Total: 12.5 kg, 3 boxes, 0.75 m", NumberString];
Total[ToExpression[nums]]
16.25

NumberString matches integers and decimals.

What's next

Try the Intermediate Projects, then continue to Level 3 — Advanced: scoping and evaluation, built-in knowledge, packages, performance, and deploying code to the cloud.