Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Page wiki
View or edit the community-maintained wiki page associated with this page.
std.regex
Regular expressions are a commonly used method of pattern matching on strings, with regex being a catchy word for a pattern in this domain specific language. Typical problems usually solved by regular expressions include validation of user input and the ubiquitous find & replace in text processing utilities. Synposis:import std.regex; import std.stdio; void main() { // Print out all possible dd/mm/yy(yy) dates found in user input. // g - global: find all matches. auto r = regex(r"\b[0-9][0-9]?/[0-9][0-9]?/[0-9][0-9](?:[0-9][0-9])?\b", "g"); foreach(line; stdin.byLine) { // Match returns a range that can be iterated // to get all subsequent matches. foreach(c; match(line, r)) writeln(c.hit); } } ... // Create a static regex at compile-time, which contains fast native code. enum ctr = ctRegex!(`^.*/([^/]+)/?$`); // It works just like a normal regex: auto m2 = match("foo/bar", ctr); // First match found here, if any assert(m2); // Be sure to check if there is a match before examining contents! assert(m2.captures[1] == "bar"); // Captures is a range of submatches: 0 = full match. ... // The result of the match is directly testable with if/assert/while. // e.g. test if a string consists of letters: assert(match("Letter", `^\p{L}+$`));The general usage guideline is to keep regex complexity on the side of simplicity, as its capabilities reside in purely character-level manipulation, and as such are ill-suited for tasks involving higher level invariants like matching an integer number bounded in an [a,b] interval. Checks of this sort of are better addressed by additional post-processing. The basic syntax shouldn't surprise experienced users of regular expressions. Thankfully, nowadays the web is bustling with resources to help newcomers, and a good reference with tutorial on regular expressions can be found. This library uses an ECMAScript syntax flavor with the following extensions:
- Named subexpressions, with Python syntax.
- Unicode properties such as Scripts, Blocks and common binary properties e.g Alphabetic, White_Space, Hex_Digit etc.
- Arbitrary length and complexity lookbehind, including lookahead in lookbehind and vise-versa.
Pattern syntax
std.regex operates on codepoint level,
'character' in this table denotes a single unicode codepoint.
Character classes
Pattern element | Semantics |
Any atom | Has the same meaning as outside of a character class. |
a-z | Includes characters a, b, c, ..., z. |
[a||b], [a--b], [a~~b], [a&&b] | Where a, b are arbitrary classes, means union, set difference, symmetric set difference, and intersection respectively. Any sequence of character class elements implicitly forms a union. |
Regex flags
UTS 18. Specifically:
- 1.1 Hex notation via any of \uxxxx, \U00YYYYYY, \xZZ.
- 1.2 Unicode properties.
- 1.3 Character classes with set operations.
- 1.4 Word boundaries use the full set of "word" characters.
- 1.5 Using simple casefolding to match case insensitively across the full range of codepoints.
- 1.6 Respecting line breaks as any of \u000A | \u000B | \u000C | \u000D | \u0085 | \u2028 | \u2029 | \u000D\u000A.
- 1.7 Operating on codepoint level.
Boost License 1.0. Authors:
Dmitry Olshansky, API and utility constructs are based on original std.regex by Walter Bright and Andrei Alexandrescu. Source:
std/regex.d
- struct Regex(Char);
- Regex object holds regular expression pattern in compiled form. Instances of this object are constructed via calls to regex. This is an intended form for caching and storage of frequently used regular expressions.
- struct StaticRegex(Char);
- A StaticRegex is Regex object that contains specially generated machine code to speed up matching. Implicitly convertible to normal Regex, however doing so will result in losing this additional capability.
- struct Captures(R, DIndex = size_t) if (isSomeString!(R));
- Captures object contains submatches captured during a call
to match or iteration over RegexMatch range.
First element of range is the whole match.
Example, showing basic operations on Captures:
import std.regex; import std.range; void main() { auto m = match("@abc#", regex(`(\w)(\w)(\w)`)); auto c = m.captures; assert(c.pre == "@"); // Part of input preceeding match assert(c.post == "#"); // Immediately after match assert(c.hit == c[0] && c.hit == "abc"); // The whole match assert(c[2] =="b"); assert(c.front == "abc"); c.popFront(); assert(c.front == "a"); assert(c.back == "c"); c.popBack(); assert(c.back == "b"); popFrontN(c, 2); assert(c.empty); }
- R pre();
- Slice of input prior to the match.
- R post();
- Slice of input immediately after the match.
- R hit();
- Slice of matched portion of input.
- R front();
R back();
void popFront();
void popBack();
const bool empty();
R opIndex()(size_t i); - Range interface.
- R opIndex(String)(String i);
- Lookup named submatch.
import std.regex; import std.range; auto m = match("a = 42;", regex(`(?P<var>\w+)\s*=\s*(?P<value>\d+);`)); auto c = m.captures; assert(c["var"] == "a"); assert(c["value"] == "42"); popFrontN(c, 2); //named groups are unaffected by range primitives assert(c["var"] =="a"); assert(c.front == "42");
- const size_t length();
- Number of matches in this object.
- @property ref auto captures();
- A hook for compatibility with original std.regex.
- struct RegexMatch(R, alias Engine = ThompsonMatcher) if (isSomeString!(R));
- A regex engine state, as returned by match family of functions.
Effectively it's a forward range of Captures!R, produced
by lazily searching for matches in a given input.
alias Engine specifies an engine type to use during matching,
and is automatically deduced in a call to match/bmatch.
- R pre();
R post();
R hit(); - Shorthands for front.pre, front.post, front.hit.
- @property auto front();
void popFront();
auto save(); - Functionality for processing subsequent matches of global regexes via range interface:
import std.regex; auto m = match("Hello, world!", regex(`\w+`, "g")); assert(m.front.hit == "Hello"); m.popFront(); assert(m.front.hit == "world"); m.popFront(); assert(m.empty);
- bool empty();
- Test if this match object is empty.
- T opCast(T : bool)();
- Same as !(x.empty), provided for its convenience in conditional statements.
- @property auto captures();
- Same as .front, provided for compatibility with original std.regex.
- R pre();
- auto regex(S)(S pattern, const(char)[] flags = "");
- Compile regular expression pattern for the later execution.
Returns:
Regex object that works on inputs having the same character width as pattern. Parameters:
Throws:pattern Regular expression flags The attributes (g, i, m and x accepted)
RegexException if there were any errors during compilation. - template ctRegex(alias pattern, alias flags = [])
- Experimental feature.
Compile regular expression using CTFE
and generate optimized native machine code for matching it.
Returns:
StaticRegex object for faster matching. Parameters:pattern Regular expression flags The attributes (g, i, m and x accepted) - auto match(R, RegEx)(R input, RegEx re);
auto match(R, String)(R input, String re); - Start matching input to regex pattern re,
using Thompson NFA matching scheme.
This is the recommended method for matching regular expression.
re parameter can be one of three types:
- Plain string, in which case it's compiled to bytecode before matching.
- Regex!char (wchar/dchar) that contains pattern in form of precompiled bytecode.
- StaticRegex!char (wchar/dchar) that contains pattern in form of specially crafted native code.
a RegexMatch object holding engine state after first match. - auto bmatch(R, RegEx)(R input, RegEx re);
auto bmatch(R, String)(R input, String re); - Start matching input to regex pattern re,
using traditional backtracking matching scheme.
re parameter can be one of three types:
- Plain string, in which case it's compiled to bytecode before matching.
- Regex!char (wchar/dchar) that contains pattern in form of precompiled bytecode.
- StaticRegex!char (wchar/dchar) that contains pattern in form of specially crafted native code.
a RegexMatch object holding engine state after first match. - R replace(alias scheme = match, R, RegEx)(R input, RegEx re, R format);
- Construct a new string from input by replacing each match with
a string generated from match according to format specifier.
To replace all occurrences use regex with "g" flag, otherwise
only the first occurrence gets replaced.
Parameters:
Example:input string to search re compiled regular expression to use format format string to generate replacements from
// Comify a number auto com = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g"); assert(replace("12000 + 42100 = 54100", com, ",") == "12,000 + 42,100 = 54,100");
The format string can reference parts of match using the following notation.Format specifier Replaced by $& the whole match. $` part of input preceding the match. $' part of input following the match. $$ '$' character. \c , where c is any character the character c itself. \\ '\' character. $1 .. $99 submatch number 1 to 99 respectively. assert(replace("noon", regex("^n"), "[$&]") == "[n]oon");
- R replace(alias fun, R, RegEx, alias scheme = match)(R input, RegEx re);
- Search string for matches using regular expression pattern re
and pass captures for each match to user-defined functor fun.
To replace all occurrances use regex with "g" flag, otherwise
only first occurrence gets replaced.
Returns:
new string with all matches replaced by return values of fun. Parameters:
Example:s string to search re compiled regular expression fun delegate to use
Capitalize the letters 'a' and 'r':string baz(Captures!(string) m) { return std.string.toUpper(m.hit); } auto s = replace!(baz)("Strap a rocket engine on a chicken.", regex("[ar]", "g")); assert(s == "StRAp A Rocket engine on A chicken.");
- struct Splitter(Range, alias RegEx = Regex) if (isSomeString!(Range) && isRegexFor!(RegEx, Range));
- Range that splits a string using a regular expression as a
separator.
Example:
auto s1 = ", abc, de, fg, hi, "; assert(equal(splitter(s1, regex(", *")), ["", "abc", "de", "fg", "hi", ""]));
- Splitter!(Range, RegEx) splitter(Range, RegEx)(Range r, RegEx pat);
- A helper function, creates a Splitter on range r separated by regex pat. Captured subexpressions have no effect on the resulting range.
- String[] split(String, RegEx)(String input, RegEx rx);
- An eager version of splitter that creates an array with splitted slices of input.
- class RegexException: object.Exception;
- Exception object thrown in case of errors during regex compilation.