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:
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.
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 writeln(c.hit); }
s
to store a string pattern. r
contains the regex
pattern. We use it to define the phrase which is to be searched in the s
string.matchAll()
function to find all the possible "the"
phrases in the string. 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" }
r
to store the regex
pattern. Note: The expressions used are
(?<=regex)
and(?=regex)
for the look-behind assertion. Whereregex \w\w\w
represents a three-character skip, one\w
for each skip.
RELATED TAGS
CONTRIBUTOR
View all Courses