PovilasB
PovilasB

Reputation: 1608

C++11 regex capture file name with optional extension

I'm using g++ 4.9.0, so it does support regular expressions :) I'm trying to extract file name with an optional extension:

#include <regex>

smatch match_result;
regex pattern("/home/user/(.+)(\\.png)?$");
if (!regex_search("/home/user/image.png", match_result, pattern) {
    throw runtime_error("Path does not match the pattern.");
}

cout << "File name: " << match_result[1] << '\n';

Running this snippet, outputs me image.png while I was expecting image. Apparently the + quantifier is greedy and ignores the following pattern (\\.png)?$. Is there anyway to avoid this? Or should I trim the extension manually?

Upvotes: 1

Views: 1825

Answers (3)

Galik
Galik

Reputation: 48635

Your code example does not use regex pattern("/home/user/(.+)(\\.png)?$"). It uses a new regex you create when you call regex_search():

regex_search("/home/user/image.png", match_result, regex("/home/user/(.+)"))

The regex you actually use does not check for the .png extension.

Try this:

regex_search("/home/user/image.png", match_result, pattern)

Upvotes: 0

Braj
Braj

Reputation: 46851

Get the matched group from index 1.

Here is DEMO

String literals for use in programs:

C#

@"\/(\w+)\.png$"

Upvotes: 0

Alexander Gelbukh
Alexander Gelbukh

Reputation: 2240

Use (.+?). The question mark makes the pattern not greedy. I guess you will also need ^.

The complete pattern: "^/home/user/(.+?)(\\.png)?$".

You may also want to use ignore-case matching.

Upvotes: 2

Related Questions