Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Searching with regular expressions


Regular expressions are a common tool to perform advanced operations on text, including complex searches, replacements, splitting, and more. Unlike JavaScript or Perl, D does not have regular expressions built into the language, but it has all the same power—and more—as those languages through the std.regex Phobos module. To explore regular expressions in D, we'll write a small program that searches stdin for a particular regex that is given on the command line and prints out the matching lines.

How to do it…

Let's use the search operation with regular expressions by executing the following steps:

  1. Create a Regex object. If you are using string literals, D's r"" or `` syntax makes it much more readable.

  2. Loop over the matches and print them out.

Pretty simple! The code is as follows:

void main(string[] args) {
    import std.regex, std.stdio;
    auto re = regex(args[1], "g");
    foreach(line; stdin.byLine)
    if(line.match(re)) writeln(line, " was a match!"...