IfCondition.
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.
| Pattern element | Semantics | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Atoms | Match single characters | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| any character except ^class | Matches a single character that
does not belong to this character class. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \cC | Matches the control character corresponding to letter C | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \xXX | Matches a character with hexadecimal value of XX. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \uXXXX | Matches a character with hexadecimal value of XXXX. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \U00YYYYYY | Matches a character with hexadecimal value of YYYYYY. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \f | Matches a formfeed character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \n | Matches a linefeed character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \r | Matches a carriage return character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \t | Matches a tab character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \v | Matches a vertical tab character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \d | Matches any Unicode digit. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \D | Matches any character except Unicode digits. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \w | Matches any word character (note: this includes numbers). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \W | Matches any non-word character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \s | Matches whitespace, same as \p{White_Space}. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \S | Matches any character except those recognized as \s . | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| \\\\ | Matches \ character. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
\c where c is one of Character classes
|
| Pattern element | Semantics |
| Any atom | Has the same meaning as outside of a character class, except for which must be written as \\] |
| 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
| Flag | Semantics |
| g | Global regex, repeat over the whole input. |
| i | Case insensitive matching. |
| m | Multi-line mode, match ^, $ on start and end line separators
as well as start and end of input. |
| s | Single-line mode, makes . match '\n' and '\r' as well. |
| x | Free-form syntax, ignores whitespace in pattern, useful for formatting complex regular expressions. |
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.
Copyright
License
Types 7
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.
Example:
Test if this object doesn't contain any compiled pattern.
Regex!char r;
assert(r.empty);
r = regex(""); // Note: "" is a valid regex pattern.
assert(!r.empty);Getting a range of all the named captures in the regex. ---- 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(nc0 == "name"); assert(nc1..$.equal("var")); ----
A StaticRegex is Regex object that contains D code specially generated at compile-time to speed up matching.
No longer used, kept as alias to Regex for backwards compatibility.
Captures object contains submatches captured during a call to match or iteration over RegexMatch range.
First element of range is the whole match.
inout(R) getMatch(size_t index) inoutvoid popFront()dittovoid popBack()dittobool opCast(T: bool)() @safe const nothrowExplicit cast to bool. Useful as a shorthand for !(x.empty) in if and assert statements.int whichPattern() @safe @property const nothrowNumber of pattern matched counting, where 1 - the first pattern. Returns 0 on no match.R opIndex(String)(String i) if (isSomeString!String)Lookup named submatch.@property ref captures(){A hook for compatibility with original std.regex.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.
Matcher!Char _engineRebindable!(const MatcherFactory!Char) _factoryR _inputCaptures!R _capturesinout(Captures!R) front() @property inoutFunctionality 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.popF...void popFront()dittoauto save(){dittoT opCast(T: bool)(){Same as !(x.empty), provided for its convenience in conditional statements.this(R input, RegEx prog)Exception object thrown in case of errors during regex compilation.
Functions 34
auto regex(S : C[], C)(const S[] patterns, const(char)[] flags = "") if (isSomeString!(S)) @trustedCompile regular expression pattern for the later execution. Returns: `Regex` object that works on inputs having the same character width as `pattern`.auto regexImpl(S)(const S pattern, const(char)[] flags = "") if (isSomeString!(typeof(pattern)))void replaceCapturesInto(alias output, Sink, R, T)(ref Sink sink, R input, T captures) if (isOutputRange!(Sink, dchar) && isSomeString!R) @trustedvoid replaceMatchesInto(alias output, Sink, R, T)(ref Sink sink, R input, T matches) if (isOutputRange!(Sink, dchar) && isSomeString!R)R replaceFirstWith(alias output, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R))R replaceAllWith(alias output,
alias method = matchAll, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R))auto match(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R))Start matching `input` to regex pattern `re`, using Thompson NFA matching scheme.auto matchFirst(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, 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.auto matchFirst(R, String)(R input, String[] re...) if (isSomeString!R && isSomeString!String)dittoauto matchAll(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, 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.auto bmatch(R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R))Start matching of `input` to regex pattern `re`, using traditional https://en.wikipedia.org/wiki/Backtracking matching scheme.void replaceFmt(R, Capt, OutR)(R format, Capt captures, OutR sink, bool ignoreBadSubs = false) if (isOutputRange!(OutR, ElementEncodingType!R[]) &&
isOutputRange!(OutR, ElementEncodingType!(Capt.String)[]))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.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 t...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)) @trustedA 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 inc...void replaceFirstInto(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re) if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R)) @trusteddittoR replaceAll(R, C, RegEx)(R input, RegEx re, const(C)[] format) if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R)) @trustedConstruct 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.R replaceAll(alias fun, R, RegEx)(R input, RegEx re) if (isSomeString!R && isRegexFor!(RegEx, R)) @trustedThis 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 t...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)) @trustedA 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 incre...void replaceAllInto(alias fun, Sink, R, RegEx)(Sink sink, R input, RegEx re) if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R)) @trusteddittoR 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))dittoSplitter!(keepSeparators, Range, RegEx) splitter(
Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, RegEx)(Range r, RegEx pat) if (
is(BasicElementOf!Range : dchar) && isRegexFor!(RegEx, Range))dittoString[] split(String, RegEx)(String input, RegEx rx) if (isSomeString!String && isRegexFor!(RegEx, String)) @trustedAn eager version of `splitter` that creates an array with splitted slices of `input`.