liveBook · Manning

Regular expression

As explained in Julia as a Second Language

A regular expression is a pattern language for specifying text sequences to search for or match.

A regular expression is a miniature pattern language for specifying text to search for or match. In Julia, it is useful when literal replacement is too broad—for example, changing the type name Rocket without also changing RocketEngine. section 11.0 section 11.4.3

Prefix a pattern with r to create a Regex object, such as r"Rocket[^A-Za-z]". Character classes describe allowed characters: . matches any character, \d a digit, \w an alphanumeric character or underscore, and \s whitespace. Quantifiers control repetition: * means zero or more, + one or more, and ? zero or one. section 11.4.3

Capture parts of a match

rx = r"\\w+ (\\d+) (\\w+) \\d+"; m = match(rx, "foo 123 bar 42") returns captures "123" and "bar", accessible as m[1] and m[2]. Named groups such as (?<hour>\\d+) can instead be retrieved with m["hour"]. section 11.4.3

Listing 11.14 Text substitution using regular expressions
julia> result = replace(s, r"Rocket[^A-Za-z]"=>"SpaceCraft");

julia> println(result)
struct RocketEngine
   thrust::Float64
   Isp::Float64
end

mutable struct SpaceCraft
   tank::Tank
   engine::RocketEngine
end

See the replacement example that preserves RocketEngine while renaming the standalone Rocket type. section 11.4.3

How Julia as a Second Language covers it

How deep it goes
Defines literals, character classes, quantifiers, matching, substitution, and captures, while limiting syntax to an overview.
Examples
Demonstrates renaming Rocket selectively, matching structured words and numbers, and extracting named hour and minute fields.
What it assumes
Assumes basic Julia string operations and introduces regular-expression notation through small runnable examples.
What you can do after
Apply it via Julia's Regex, match, and replace operations to locate, extract, and selectively substitute text.
How it connects
Connects raw strings, string replacement, pattern matching, character classes, quantifiers, and captured groups.

Also explained in

Compare how 27 books explain regular expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.