Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In D using the std.regex library, how do you match a dot?

Tags:

regex

d

This may sound like a silly question but in D (using std.regex) how do you match a literal dot in a string?

Using this code i'm checking for the file extension .bmp so i perform a simple regex match on it. If i try and escape the dot like this i get an error.

Regex!char Pattern = regex("\.bmp$", "i");

if (match(FileName, Pattern).empty)
{
    FileName ~= ".bmp";
}

Error: Undefined escape sequence \.

Even in the documentation it doesn't mention matching dots.

Any ideas?

like image 668
Gary Willoughby Avatar asked Dec 31 '11 12:12

Gary Willoughby


1 Answers

Your "\.bmp$" string is escaped itself, hence the error. D thinks you are trying to escape the . in the string, but \. isn't a valid escape sequence.

Note that this isn't specific to D; C++ gives you the same error.

const char* regex = "\.bmp$";  

Compiling with g++ 4.3.4 gives:

prog.cpp:1: error: unknown escape sequence '\.'

You have two options:

  1. Escape the \ in your string i.e. "\\.bmp$".
  2. Use a raw string literator i.e. r"\.bmp$". Raw string literals ignore all escape sequences. They are designed specifically for things like regex patterns.
like image 69
Peter Alexander Avatar answered Nov 14 '22 22:11

Peter Alexander