Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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 usinga local clone.

std.regex

Regular expressions are a commonly used method of pattern matching on strings, withregex 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.
CategoryFunctions
MatchingbmatchmatchmatchAllmatchFirst
BuildingctRegexescaperregex
ReplacereplacereplaceAllreplaceAllIntoreplaceFirstreplaceFirstInto
Splitsplitsplitter
ObjectsCapturesRegexRegexExceptionRegexMatchSplitterStaticRegex

Synopsis

Create a regex at runtime:
They met on 24/01/1970.7/8/99 wasn't as hot as 7/8/2022.
import std.regex;import std.stdio;// 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:
import std.regex;auto ctr = ctRegex!(`^.*/([^/]+)/?$`);// It works just like a normal regex:auto c2 = matchFirst("foo/bar", ctr);// First match found here, if anyassert(!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.
Multi-pattern regex:
import std.regex;auto multi =regex([`\d+,\d+`,`([a-z]+):(\d+)`]);auto m ="abc:43 12,34".matchAll(multi);assert(m.front.whichPattern == 2);assert(m.front[1] =="abc");assert(m.front[2] =="43");m.popFront();assert(m.front.whichPattern == 1);assert(m.front[0] =="12,34");
Captures andopCast!bool:
import std.regex;// The result of `matchAll/matchFirst` is directly testable with `if/assert/while`,// e.g. test if a string consists of letters only:assert(matchFirst("LettersOnly",`^\p{L}+$`));// And we can take advantage of the ability to define a variable in the IfCondition:if (const captures = matchFirst("At l34st one digit, but maybe more...",`((\d)(\d*))`)){assert(captures[2] =="3");assert(captures[3] =="4");assert(captures[1] =="34");}
See Also:
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 numberbounded 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 tostd.regex see ashort tour of the module API and its abilities.
There are other web resources on regular expressions to help newcomers, and a goodreference 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 elementSemantics
AtomsMatch single characters
any character except [{|*+?()^$Matches the character itself.
.In single line mode matches any character. Otherwise it matches any character except '\n' and '\r'.
[class]Matches a single character that belongs to this character class.
[^class]Matches a single character that doesnot belong to this character class.
\cCMatches the control character corresponding to letter C
\xXXMatches a character with hexadecimal value of XX.
\uXXXXMatches a character with hexadecimal value of XXXX.
\U00YYYYYYMatches a character with hexadecimal value of YYYYYY.
\fMatches a formfeed character.
\nMatches a linefeed character.
\rMatches a carriage return character.
\tMatches a tab character.
\vMatches a vertical tab character.
\dMatches any Unicode digit.
\DMatches any character except Unicode digits.
\wMatches any word character (note: this includes numbers).
\WMatches any non-word character.
\sMatches whitespace, same as \p{White_Space}.
\SMatches any character except those recognized as\s.
\\Matches \ character.
\c where c is one of [|*+?()Matches the character c itself.
\p{PropertyName}Matches a character that belongs to the Unicode PropertyName set. Single letter abbreviations can be used without surrounding {,}.
\P{PropertyName}Matches a character that does not belong to the Unicode PropertyName set. Single letter abbreviations can be used without surrounding {,}.
\p{InBasicLatin}Matches any character that is part of the BasicLatin Unicodeblock.
\P{InBasicLatin}Matches any character except ones in the BasicLatin Unicodeblock.
\p{Cyrillic}Matches any character that is part of Cyrillicscript.
\P{Cyrillic}Matches any character except ones in Cyrillicscript.
QuantifiersSpecify repetition of other elements
*Matches previous character/subexpression 0 or more times. Greedy version - tries as many times as possible.
*?Matches previous character/subexpression 0 or more times. Lazy version - stops as early as possible.
+Matches previous character/subexpression 1 or more times. Greedy version - tries as many times as possible.
+?Matches previous character/subexpression 1 or more times. Lazy version - stops as early as possible.
?Matches previous character/subexpression 0 or 1 time. Greedy version - tries as many times as possible.
??Matches previous character/subexpression 0 or 1 time. Lazy version - stops as early as possible.
{n}Matches previous character/subexpression exactly n times.
{n,}Matches previous character/subexpression n times or more. Greedy version - tries as many times as possible.
{n,}?Matches previous character/subexpression n times or more. Lazy version - stops as early as possible.
{n,m}Matches previous character/subexpression n to m times. Greedy version - tries as many times as possible, but no more than m times.
{n,m}?Matches previous character/subexpression n to m times. Lazy version - stops as early as possible, but no less then n times.
OtherSubexpressions & alternations
(regex) Matches subexpression regex, saving matched portion of text for later retrieval.
(?#comment)An inline comment that is ignored while matching.
(?:regex)Matches subexpression regex,not saving matched portion of text. Useful to speed up matching.
A|BMatches subexpression A, or failing that, matches B.
(?P<name>regex)Matches named subexpression regex labeling it with name 'name'. When referring to a matched portion of text, names work like aliases in addition to direct numbers.
AssertionsMatch position rather than character
^Matches at the beginning of input or line (in multiline mode).
$Matches at the end of input or line (in multiline mode).
\bMatches at word boundary.
\BMatches whennot at word boundary.
(?=regex)Zero-width lookahead assertion. Matches at a point where the subexpression regex could be matched starting from the current position.
(?!regex)Zero-width negative lookahead assertion. Matches at a point where the subexpression regex couldnot be matched starting from the current position.
(?<=regex)Zero-width lookbehind assertion. Matches at a point where the subexpression regex could be matched ending at the current position (matching goes backwards).
(?<!regex)Zero-width negative lookbehind assertion. Matches at a point where the subexpression regex couldnot be matched ending at the current position (matching goes backwards).

Character classes

Pattern elementSemantics
Any atomHas the same meaning as outside of a character class, except for ] which must be written as \]
a-zIncludes 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

FlagSemantics
gGlobal regex, repeat over the whole input.
iCase insensitive matching.
mMulti-line mode, match ^, $ on start and end line separators as well as start and end of input.
sSingle-line mode, makes . match '\n' and '\r' as well.
xFree-form syntax, ignores whitespace in pattern, useful for formatting complex regular expressions.

Unicode support

This library provides full Level 1 support* according toUTS 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.
*With exception of point 1.1.1, as of yet, normalization of input is expected to be enforced by user.

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 theformat argument ofreplaceFirst andreplaceAll.
The format string can reference parts of match using the following notation.
Format specifierReplaced by
$&the whole match.
$`part of inputpreceding the match.
$'part of inputfollowing the match.
$$'$' character.
\c , where c is any characterthe character c itself.
\\'\' character.
$1 .. $99submatch 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 thereplace family of functions that generate a new string from the input.
In cases where producing the replacement is the ultimate goalreplaceFirstInto andreplaceAllInto could come in handy as functions that avoid allocations even for replacement.
License:
Boost License 1.0.
Authors:
Dmitry Olshansky,
API and utility constructs are modeled after the originalstd.regex by Walter Bright and Andrei Alexandrescu.

Sourcestd/regex/package.d

templateRegex(Char)
Regex object holds regular expression pattern in compiled form.
Instances of this object are constructed via calls toregex. 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;staticassert(isRandomAccessRange!(typeof(nc)));assert(!nc.empty);assert(nc.length == 2);assert(nc.equal(["name","var"]));assert(nc[0] =="name");assert(nc[1..$].equal(["var"]));

aliasStaticRegex = Regex(Char);
AStaticRegex isRegex 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.
@trusted autoregex(S : C[], C)(const S[]patterns, const(char)[]flags = "")
if (isSomeString!S);

@trusted autoregex(S)(Spattern, 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 aspattern.
Parameters:
SpatternA single regular expression to match.
S[]patternsAn array of regular expression strings. The resultingRegex object will match any expression; usewhichPattern to know which.
const(char)[]flagsThe attributes (g, i, m, s and x accepted)
Throws:
RegexException if there were any errors during compilation.
Examples:
void test(S)(){// multi-pattern regex example    S[] arr = [`([a-z]+):(\d+)`,`(\d+),\d+`];auto multi =regex(arr);// multi regex    S str ="abc:43 12,34";auto m = str.matchAll(multi);    writeln(m.front.whichPattern);// 1    writeln(m.front[1]);// "abc"    writeln(m.front[2]);// "43"    m.popFront();    writeln(m.front.whichPattern);// 2    writeln(m.front[1]);// "12"}import std.meta : AliasSeq;staticforeach (C; AliasSeq!(string, wstring, dstring))// Test with const array of patterns - see https://issues.dlang.org/show_bug.cgi?id=20301staticforeach (S; AliasSeq!(C,const C,immutable C))        test!S();
enum autoctRegex(alias pattern, string flags = "");
Compile regular expression using CTFE and generate optimized native machine code for matching it.
Returns:
StaticRegex object for faster matching.
Parameters:
patternRegular expression
flagsThe attributes (g, i, m, s and x accepted)
structCaptures(R) if (isSomeString!R);
Captures object contains submatches captured during a call tomatch or iteration overRegexMatch range.
First element of range is the whole match.
Examples:
import std.range.primitives : popFrontN;auto c = matchFirst("@abc#", regex(`(\w)(\w)(\w)`));assert(c.pre =="@");// Part of input preceding matchassert(c.post =="#");// Immediately after matchassert(c.hit == c[0] && c.hit =="abc");// The whole matchwriteln(c[2]);// "b"writeln(c.front);// "abc"c.popFront();writeln(c.front);// "a"writeln(c.back);// "c"c.popBack();writeln(c.back);// "b"popFrontN(c, 2);assert(c.empty);assert(!matchFirst("nothing","something"));// Captures that are not matched will be null.c = matchFirst("ac", regex(`a(b)?c`));assert(c);assert(!c[1]);
@property Rpre();
Slice of input prior to the match.
@property Rpost();
Slice of input immediately after the match.
@property Rhit();
Slice of matched portion of input.
@property Rfront();

@property Rback();

voidpopFront();

voidpopBack();

@property boolempty() const;

inout(R)opIndex()(size_ti) inout;
Range interface.
nothrow @safe boolopCast(T : bool)() const;
Explicit cast to bool. Useful as a shorthand for !(x.empty) in if and assert statements.
import std.regex;assert(!matchFirst("nothing","something"));
nothrow @property @safe intwhichPattern() const;
Number of pattern matched counting, where 1 - the first pattern. Returns 0 on no match.
Examples:
import std.regex;writeln(matchFirst("abc","[0-9]+","[a-z]+").whichPattern);// 2
RopIndex(String)(Stringi)
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 primitivesassert(c["var"] =="a");assert(c.front =="42");
@property size_tlength() const;
Number of matches in this object.
@property ref autocaptures();
A hook for compatibility with original std.regex.
structRegexMatch(R) if (isSomeString!R);
A regex engine state, as returned bymatch family of functions.
Effectively it's a forward range of Captures!R, produced by lazily searching for matches in a given input.
@property Rpre();

@property Rpost();

@property Rhit();
Shorthands for front.pre, front.post, front.hit.
@property inout(Captures!R)front() inout;

voidpopFront();

autosave();
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 boolempty() const;
Test if this match object is empty.
TopCast(T : bool)();
Same as !(x.empty), provided for its convenience in conditional statements.
@property inout(Captures!R)captures() inout;
Same as .front, provided for compatibility with original std.regex.
automatch(R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));

automatch(R, String)(Rinput, Stringre)
if (isSomeString!R && isSomeString!String);
Start matchinginput to regex patternre, using Thompson NFA matching scheme.
The use of this function isdiscouraged - use either ofmatchAll ormatchFirst.
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:
aRegexMatch object holding engine state after first match.
automatchFirst(R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));

automatchFirst(R, String)(Rinput, Stringre)
if (isSomeString!R && isSomeString!String);

automatchFirst(R, String)(Rinput, String[]re...)
if (isSomeString!R && isSomeString!String);
Find the first (leftmost) slice of theinput that matches the patternre. This function picks the most suitable regular expression engine depending on the pattern properties.
re parameter can be one of three types:
  • Plain string(s), 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:
Captures containing the extent of a match together with all submatches if there was a match, otherwise an emptyCaptures object.
automatchAll(R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));

automatchAll(R, String)(Rinput, Stringre)
if (isSomeString!R && isSomeString!String);

automatchAll(R, String)(Rinput, String[]re...)
if (isSomeString!R && isSomeString!String);
Initiate a search for all non-overlapping matches to the patternre in the giveninput. 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(s), 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.
autobmatch(R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));

autobmatch(R, String)(Rinput, Stringre)
if (isSomeString!R && isSomeString!String);
Start matching ofinput to regex patternre, using traditional backtracking matching scheme.
The use of this function isdiscouraged - use either ofmatchAll ormatchFirst.
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:
aRegexMatch object holding engine state after first match.
RreplaceFirst(R, C, RegEx)(Rinput, RegExre, const(C)[]format)
if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
Construct a new string frominput by replacing the first match with a string generated from it according to theformat specifier.
To replace all matches usereplaceAll.
Parameters:
Rinputstring to search
RegExrecompiled regular expression to use
const(C)[]formatformat string to generate replacements from, seethe 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.
Examples:
writeln(replaceFirst("noon", regex("n"),"[$&]"));// "[n]oon"
RreplaceFirst(alias fun, R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));
This is a general replacement tool that construct a new string by replacing matches of patternre in theinput. Unlike the other overload there is no format string instead captures are passed to to a user-defined functorfun that returns a new string to use as replacement.
This version replaces the first match ininput, seereplaceAll to replace the all of the matches.
Returns:
A new string of the same type asinput with all matches replaced by return values offun. If no matches found returns theinput itself.
Examples:
import std.conv : to;string list ="#21 out of 46";string newList =replaceFirst!(cap => to!string(to!int(cap.hit)+1))    (list, regex(`[0-9]+`));writeln(newList);// "#22 out of 46"
@trusted voidreplaceFirstInto(Sink, R, C, RegEx)(ref Sinksink, Rinput, RegExre, const(C)[]format)
if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));

@trusted voidreplaceFirstInto(alias fun, Sink, R, RegEx)(Sinksink, Rinput, RegExre)
if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R));
A variation onreplaceFirst that instead of allocating a new string on each call outputs the result piece-wise to thesink. In particular this enables efficient construction of a final output incrementally.
Like inreplaceFirst family of functions there is an overload for the substitution guided by theformat string and the one with the user defined callback.
Examples:
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 callbackreplaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`));writeln(result.data);// "first\nsecond\n"
@trusted RreplaceAll(R, C, RegEx)(Rinput, RegExre, const(C)[]format)
if (isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));
Construct a new string frominput by replacing all of the fragments that match a patternre with a string generated from the match according to theformat specifier.
To replace only the first match usereplaceFirst.
Parameters:
Rinputstring to search
RegExrecompiled regular expression to use
const(C)[]formatformat string to generate replacements from, seethe format string.
Returns:
A string of the same type asinput with the all of the matches (if any) replaced. If no match is found returns the input string itself.
Examples:
// insert comma as thousands delimiterautore = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g");writeln(replaceAll("12000 + 42100 = 54100",re,","));// "12,000 + 42,100 = 54,100"
@trusted RreplaceAll(alias fun, R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));
This is a general replacement tool that construct a new string by replacing matches of patternre in theinput. Unlike the other overload there is no format string instead captures are passed to to a user-defined functorfun that returns a new string to use as replacement.
This version replaces all of the matches found ininput, seereplaceFirst to replace the first match only.
Returns:
A new string of the same type asinput with all matches replaced by return values offun. If no matches found returns theinput itself.
Parameters:
Rinputstring to search
RegExrecompiled regular expression
fundelegate to use
Examples:
string baz(Captures!(string) m){import std.string : toUpper;return toUpper(m.hit);}// Capitalize the letters 'a' and 'r':auto s =replaceAll!(baz)("Strap a rocket engine on a chicken.",        regex("[ar]"));writeln(s);// "StRAp A Rocket engine on A chicken."
@trusted voidreplaceAllInto(Sink, R, C, RegEx)(Sinksink, Rinput, RegExre, const(C)[]format)
if (isOutputRange!(Sink, dchar) && isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R));

@trusted voidreplaceAllInto(alias fun, Sink, R, RegEx)(Sinksink, Rinput, RegExre)
if (isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R));
A variation onreplaceAll that instead of allocating a new string on each call outputs the result piece-wise to thesink. In particular this enables efficient construction of a final output incrementally.
As withreplaceAll there are 2 overloads - one with a format string, the other one with a user defined functor.
Examples:
// insert comma as thousands delimiter in fifty randomly produced big numbersimport std.array, std.conv, std.random, std.range;staticre = regex(`(?<=\d)(?=(\d\d\d)+\b)`,"g");autosink = appender!(char [])();enumulong min = 10UL ^^ 10, max = 10UL ^^ 19;foreach (i; 0 .. 50){sink.clear();replaceAllInto(sink, text(uniform(min, max)),re,",");foreach (pos; iota(sink.data.length - 4, 0, -4))        writeln(sink.data[pos]);// ','}
Rreplace(alias scheme = match, R, C, RegEx)(Rinput, RegExre, const(C)[]format)
if (isSomeString!R && isRegexFor!(RegEx, R));

Rreplace(alias fun, R, RegEx)(Rinput, RegExre)
if (isSomeString!R && isRegexFor!(RegEx, R));
Old API for replacement, operation depends on flags of patternre. With "g" flag it performs the equivalent ofreplaceAll otherwise it works the same asreplaceFirst.
The use of this function isdiscouraged, please usereplaceAll orreplaceFirst explicitly.
structSplitter(Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, alias RegEx = Regex) if (isSomeString!Range && isRegexFor!(RegEx, Range));

Splitter!(keepSeparators, Range, RegEx)splitter(Flag!"keepSeparators" keepSeparators = No.keepSeparators, Range, RegEx)(Ranger, RegExpat)
if (is(BasicElementOf!Range : dchar) && isRegexFor!(RegEx, Range));
Splits a stringr using a regular expressionpat as a separator.
Parameters:
keepSeparatorsflag to specify if the matches should be in the resulting range
Rangerthe string to split
RegExpatthe pattern to split on
Returns:
A lazy range of strings
Examples:
import std.algorithm.comparison : equal;auto s1 =", abc, de,  fg, hi, ";assert(equal(splitter(s1, regex(", *")),    ["","abc","de","fg","hi",""]));
Examples:
Split on a pattern, but keep the matches in the resulting range
import std.algorithm.comparison : equal;import std.typecons : Yes;auto pattern = regex(`([\.,])`);assert("2003.04.05"    .splitter!(Yes.keepSeparators)(pattern)    .equal(["2003",".","04",".","05"]));assert(",1,2,3"    .splitter!(Yes.keepSeparators)(pattern)    .equal([",","1",",","2",",","3"]));
@property Rangefront();

@property boolempty();

voidpopFront();

@property autosave();
Forward range primitives.
@trusted String[]split(String, RegEx)(Stringinput, RegExrx)
if (isSomeString!String && isRegexFor!(RegEx, String));
An eager version ofsplitter that creates an array with splitted slices ofinput.
aliasRegexException = std.regex.internal.ir.RegexException;
Exception object thrown in case of errors during regex compilation.
autoescaper(Range)(Ranger);
A range that lazily produces a string output escaped to be used inside of a regular expression.
Examples:
import std.algorithm.comparison;import std.regex;string s =`This is {unfriendly} to *regex*`;assert(s.escaper.equal(`This is \{unfriendly\} to \*regex\*`));
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 17:59:25 2026

[8]ページ先頭

©2009-2026 Movatter.jp