In D, using the std.regex library, how do you map the point?

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

Using this code, I check the .bmp file extension, so I execute a simple regular expression on it. If I try to avoid a point 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, he does not mention matching points.

Any ideas?

+6
source share
2 answers

I think you need to double his escape (you want \. In regex). In your current code, you are alone avoiding it, so D is trying to interpret it as something for yourself, not a regular expression. Double escaping tells D that you want to get a literal \ in a string.

So, in the end, it should look like "\\.bmp$" .

+8
source

Your line "\.bmp$" escaped by itself, hence the error. D thinks you are trying to avoid . in line, but \. is not a valid escape sequence.

Note that this does not apply 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:

  • Escape \ in your line, i.e. "\\.bmp$" .
  • Use a string writer, i.e. r"\.bmp$" . String literals ignore all escape sequences. They are designed specifically for things like regex patterns.
+10
source

Source: https://habr.com/ru/post/904803/


All Articles