Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d language

What are regular expressions in D?

Sher Ali


Regular expressions (also known as Regex) is an advanced tool used for defining search patterns for strings of text. There are three main functionalities of regex, as mentioned below:

  • Matching
  • Searching
  • Modification

In matching, we test if the entire string matches the given pattern. Searching, on the other hand, is more versatile and can be used to search for specific patterns within a string. Modification, as the name suggests, is used for string manipulation; operations like search and replace, delete, split, and trim fall into this category.


We need to use the std.regex library to access its functionality. Now, we'll see some coding examples for regex usage.

1. Search

We are implementing the matchAll(s,r) function, where s is the string and r is the phrase that we want to search within the string s. You can do this with the coding widget attached below by changing the text in s and r.

import std.regex;
import std.stdio;
void main()
    // Print out all the "the" sets in the given string.
    auto s = "Educative is the best platform in the world"; // string
    auto r = regex("the"); //phrase to be searched in the string
    foreach (c; matchAll(s, r)) //implimentaiton of matchAll function
Coding example for search


  • Line 6: We define the auto variable as s to store a string pattern.
  • Line 7: The auto variable r contains the regex pattern. We use it to define the phrase which is to be searched in the s string.
  • Line 8: We implement the matchAll() function to find all the possible "the" phrases in the string.

2. Insertion

The replaceAll(x,y,z) function is used in this exercise, where x is the string needed to be modified, y is the Regex pattern, and z is the phrase to be inserted.

The following code adds a "+" after every third character from the end of the string.

import std.regex;
import std.stdio;
void main()
    // insert + as after every third character from the end
    auto r = regex(r"(?<=\w)(?=(\w\w\w)+\b)");
    writeln(replaceAll("Educative", r, "+")); // "Edu+cat+ive"

coding example for insertion


  • Line 6: We use the auto variable r to store the regex pattern.

Note: The expressions used are (?<=regex)and(?=regex) for the look-behind assertion. Where regex \w\w\w represents a three-character skip, one \w for each skip.

  • Line 7: We implement the function replaceAll() and print the output.


d language

View all Courses

Keep Exploring