Regular Expressions in D Programming Language

Our first program demonstrates the use of regular expressions in D. Here’s the full source code:

import std.stdio;
import std.regex;

void main()
{
    // This tests whether a pattern matches a string.
    auto match = matchFirst("peach", r"p([a-z]+)ch");
    writeln(match);

    // Above we used a string pattern directly, but for
    // other regex tasks you'll need to compile an
    // optimized Regex object.
    auto r = regex(r"p([a-z]+)ch");

    // Many methods are available on these objects. Here's
    // a match test like we saw earlier.
    writeln(matchFirst("peach", r));

    // This finds the match for the regex.
    writeln(matchFirst("peach punch", r));

    // This also finds the first match but returns the
    // start and end indexes for the match instead of the
    // matching text.
    auto m = matchFirst("peach punch", r);
    writeln("idx:", [m.pre.length, m.pre.length + m.hit.length]);

    // The matchAll function returns information about
    // both the whole-pattern matches and the submatches
    // within those matches.
    foreach(c; matchAll("peach punch pinch", r))
    {
        writeln(c.hit, " ", c[1]);
    }

    // The replaceAll function can be used to replace
    // subsets of strings with other values.
    writeln(replaceAll("a peach", r, "<fruit>"));

    // The replaceFirstIn function allows you to transform matched
    // text with a given delegate.
    string result = replaceFirstIn("a peach", r, (m) => m.hit.toUpper);
    writeln(result);
}

To run the program, save it as regular_expressions.d and use the D compiler:

$ dmd regular_expressions.d
$ ./regular_expressions

This will output:

["peach", "ea"]
["peach", "ea"]
["peach", "ea"]
idx:[0, 5]
peach ea
punch un
pinch in
a <fruit>
a PEACH

For a complete reference on D regular expressions, check the std.regex module documentation.

In D, regular expressions are provided by the std.regex module. The syntax is similar to other languages, but there are some D-specific features and functions.

The regex function is used to compile a regular expression pattern into an optimized object. The matchFirst function is used for finding the first match, while matchAll can be used to find all matches.

D provides powerful string manipulation functions like replaceAll and replaceFirstIn for working with regular expressions. The replaceFirstIn function allows you to use a delegate to transform the matched text, which provides great flexibility.

Remember that D uses \ as an escape character in strings, so it’s often convenient to use raw string literals (prefixed with r) for regex patterns to avoid having to escape backslashes.