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
Intro
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.Synopsis
import std.regex; import std.stdio; void main() { // Print out all possible dd/mm/yy(yy) dates found in user input. auto r = regex(r"\b[0-9][0-9]?/[0-9][0-9]?/[0-9][0-9](?:[0-9][0-9])?\b"); foreach(line; stdin.byLine) { // matchAll() returns a range that can be iterated // to get all subsequent matches. foreach(c; matchAll(line, r)) writeln(c.hit); } } ... // Create a static regex at compile-time, which contains fast native code. auto ctr = ctRegex!(`^.*/([^/]+)/?$`); // It works just like a normal regex: auto c2 = matchFirst("foo/bar", ctr); // First match found here, if any assert(!c2.empty); // Be sure to check if there is a match before examining contents! assert(c2[1] == "bar"); // Captures is a range of submatches: 0 = full match. ... // The result of the $(D matchAll) is directly testable with if/assert/while. // e.g. test if a string consists of letters: assert(matchFirst("Letter", `^\p{L}+$`));
Syntax and general information
The general usage guideline is to keep regex complexity on the side of simplicity, as its capabilities reside in purely character-level manipulation. As such it's 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. For an introduction to std.regex see a short tour of the module API and its abilities. There are other web resources on regular expressions to help newcomers, and a good reference with tutorial can easily be found. This library uses a remarkably common 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
Unicode support
This library provides full Level 1 support* according to 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.
Replace format string
A set of functions in this module that do the substitution rely on a simple format to guide the process. In particular the table below applies to the format argument of replaceFirst and replaceAll. 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. |
Slicing and zero memory allocations orientation
All matches returned by pattern matching functionality in this library are slices of the original input. The notable exception is the replace family of functions that generate a new string from the input. In cases where producing the replacement is the ultimate goal replaceFirstInto and replaceAllInto could come in handy as functions that avoid allocations even for replacement.License:
Authors:
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.
- const nothrow @property @safe bool empty();
- Test if this object doesn't contain any compiled pattern.
Example:
Regex!char r; assert(r.empty); r = regex(""); // Note: "" is a valid regex pattern. assert(!r.empty);
- @property @safe auto namedCaptures();
- A range of all the named captures in the regex.
Example:
import std.range; import std.algorithm; auto re = regex(`(?P<name>\w+) = (?P<var>\d+)`); auto nc = re.namedCaptures; static assert(isRandomAccessRange!(typeof(nc))); assert(!nc.empty); assert(nc.length == 2); assert(nc.equal(["name", "var"])); assert(nc[0] == "name"); assert(nc[1..$].equal(["var"]));
- struct StaticRegex(Char);
- 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.
- @property R pre();
- Slice of input prior to the match.
- @property R post();
- Slice of input immediately after the match.
- @property R hit();
- Slice of matched portion of input.
- @property R front();
@property R back();
void popFront();
void popBack();
const @property bool empty();
R opIndex()(size_t i); - Range interface.
- const nothrow @safe bool opCast(T : bool)();
- Explicit cast to bool. Useful as a shorthand for !(x.empty) in if and assert statements.
import std.regex; assert(!matchFirst("nothing", "something"));
- R opIndex(String)(String i) if (isSomeString!String);
- Lookup named submatch.
import std.regex; import std.range; auto c = matchFirst("a = 42;", regex(`(?P<var>\w+)\s*=\s*(?P<value>\d+);`)); 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 @property 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.
- @property R pre();
@property R post();
@property R hit(); - @property auto front();
void popFront();
auto save(); - Functionality for processing subsequent matches of global regexes via range interface:
import std.regex; auto m = matchAll("Hello, world!", regex(`\w+`)); assert(m.front.hit == "Hello"); m.popFront(); assert(m.front.hit == "world"); m.popFront(); assert(m.empty);
- @property bool 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.
- @property R pre();
- @trusted auto regex(S)(S pattern, const(char)[] flags = "") if (isSomeString!S);
- Compile regular expression pattern for the later execution.Returns:Regex object that works on inputs having the same character width as pattern.Parameters:
S pattern Regular expression const(char)[] flags The attributes (g, i, m and x accepted) Throws:RegexException if there were any errors during compilation. - template ctRegex(alias pattern, alias flags = [])
- 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) if (isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)));
- Start matching input to regex pattern re, using Thompson NFA matching scheme.The use of this function is discouraged - use either of matchAll or matchFirst. Delegating the kind of operation to "g" flag is soon to be phased out along with the ability to choose the exact matching scheme. The choice of matching scheme to use depends highly on the pattern kind and can done automatically on case by case basis.
- auto match(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
- ditto
- auto matchFirst(R, RegEx)(R input, RegEx re) if (isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)));
- Find the first (leftmost) slice of the input that matches the pattern re. This function picks the most suitable regular expression engine depending on the pattern properties.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 a pattern in the form of compiled bytecode.
- StaticRegex!char (wchar/dchar) that contains a pattern in the form of compiled native machine code.
- auto matchFirst(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
- ditto
- auto matchAll(R, RegEx)(R input, RegEx re) if (isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)));
- Initiate a search for all non-overlapping matches to the pattern re in the given input. The result is a lazy range of matches generated as they are encountered in the input going left to right.This function picks the most suitable regular expression engine depending on the pattern properties. 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 a pattern in the form of compiled bytecode.
- StaticRegex!char (wchar/dchar) that contains a pattern in the form of compiled native machine code.
Returns:RegexMatch object that represents matcher state after the first match was found or an empty one if not present. - auto matchAll(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
- ditto
- auto bmatch(R, RegEx)(R input, RegEx re) if (isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)));
-
The use of this function is discouraged - use either of matchAll or matchFirst. Delegating the kind of operation to "g" flag is soon to be phased out along with the ability to choose the exact matching scheme. The choice of matching scheme to use depends highly on the pattern kind and can done automatically on case by case basis.Returns:a RegexMatch object holding engine state after first match.
- auto bmatch(R, String)(R input, String re) if (isSomeString!R && isSomeString!String);
- ditto
- R replaceFirst(R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
- Construct a new string from input by replacing the first match with a string generated from it according to the format specifier.To replace all matches use replaceAll.Parameters:
R input string to search RegEx re compiled regular expression to use const(C)[] format format string to generate replacements from, see the format string. Returns:A string of the same type with the first match (if any) replaced. If no match is found returns the input string itself.Example:
assert(replaceFirst("noon", regex("n"), "[$&]") == "[n]oon");
- R replaceFirst(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
- This is a general replacement tool that construct a new string by replacing matches of pattern re in the input. Unlike the other overload there is no format string instead captures are passed to to a user-defined functor fun that returns a new string to use as replacement.This version replaces the first match in input, see replaceAll to replace the all of the matches.Returns:A new string of the same type as input with all matches replaced by return values of fun. If no matches found returns the input itself.
Example:
string list = "#21 out of 46"; string newList = replaceFirst!(cap => to!string(to!int(cap.hit)+1)) (list, regex(`[0-9]+`)); assert(newList == "#22 out of 46");
- @trusted void replaceFirstInto(Sink, R, C, RegEx)(ref Sink sink, R input, RegEx re, const(C)[] format) if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
- A variation on replaceFirst that instead of allocating a new string on each call outputs the result piece-wise to the sink. In particular this enables efficient construction of a final output incrementally.Like in replaceFirst family of functions there is an overload for the substitution guided by the format string and the one with the user defined callback.
Example:
import std.array; string m1 = "first message\n"; string m2 = "second message\n"; auto result = appender!string(); replaceFirstInto(result, m1, regex(`([a-z]+) message`), "$1"); //equivalent of the above with user-defined callback replaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`)); assert(result.data == "first\nsecond\n");
- @trusted void replaceFirstInto(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re) if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R));
- ditto
- @trusted R replaceAll(R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
- Construct a new string from input by replacing all of the fragments that match a pattern re with a string generated from the match according to the format specifier.To replace only the first match use replaceFirst.Parameters:
R input string to search RegEx re compiled regular expression to use const(C)[] format format string to generate replacements from, see the format string. Returns:A string of the same type as input with the all of the matches (if any) replaced. If no match is found returns the input string itself.Example:
// Comify a number auto com = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g"); assert(replaceAll("12000 + 42100 = 54100", com, ",") == "12,000 + 42,100 = 54,100");
- @trusted R replaceAll(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
- This is a general replacement tool that construct a new string by replacing matches of pattern re in the input. Unlike the other overload there is no format string instead captures are passed to to a user-defined functor fun that returns a new string to use as replacement.This version replaces all of the matches found in input, see replaceFirst to replace the first match only.Returns:A new string of the same type as input with all matches replaced by return values of fun. If no matches found returns the input itself.Parameters:
R input string to search RegEx re compiled regular expression fun delegate to use Example: Capitalize the letters 'a' and 'r':
string baz(Captures!(string) m) { return std.string.toUpper(m.hit); } auto s = replaceAll!(baz)("Strap a rocket engine on a chicken.", regex("[ar]")); assert(s == "StRAp A Rocket engine on A chicken.");
- @trusted void replaceAllInto(Sink, R, C, RegEx)(Sink sink, R input, RegEx re, const(C)[] format) if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
- A variation on replaceAll that instead of allocating a new string on each call outputs the result piece-wise to the sink. In particular this enables efficient construction of a final output incrementally.As with replaceAll there are 2 overloads - one with a format string, the other one with a user defined functor.
Example:
//swap all 3 letter words and bring it back string text = "How are you doing?"; auto sink = appender!(char[])(); replaceAllInto!(cap => retro(cap[0]))(sink, text, regex(`\b\w{3}\b`)); auto swapped = sink.data.dup; // make a copy explicitly assert(swapped == "woH era uoy doing?"); sink.clear(); replaceAllInto!(cap => retro(cap[0]))(sink, swapped, regex(`\b\w{3}\b`)); assert(sink.data == text);
- @trusted void replaceAllInto(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re) if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R));
- ditto
- R replace(alias scheme = match, R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && isRegexFor!(RegEx, R));
- Old API for replacement, operation depends on flags of pattern re. With "g" flag it performs the equivalent of replaceAll otherwise it works the same as replaceFirst.
- R replace(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R));
- ditto
- 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) if (is(BasicElementOf!Range : dchar) && isRegexFor!(RegEx, Range));
- A helper function, creates a Splitter on range r separated by regex pat. Captured subexpressions have no effect on the resulting range.
- @trusted String[] split(String, RegEx)(String input, RegEx rx) if (isSomeString!String && isRegexFor!(RegEx, String));
- 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.