Vihaan Verma
Vihaan Verma

Reputation: 13143

boost regex to extract a number from string

I have a string resource = "/Music/1" the string can take multiple numeric values after "/Music/" . I new to regular expression stuff . I tried following code

#include <iostream>

#include<boost/regex.hpp>

int main()
{
    std::string resource = "/Music/123";

    const char * pattern = "\\d+";

    boost::regex re(pattern);

    boost::sregex_iterator it(resource.begin(), resource.end(), re);
    boost::sregex_iterator end;

    for( ; it != end; ++it)
    {
        std::cout<< it->str() <<"\n";
    }
    return 0;
}

vickey@tb:~/trash/boost$ g++ idExtraction.cpp  -lboost_regex
vickey@tb:~/trash/boost$ ./a.out 
123

works fine . But even when the string happens to be something like "/Music23/123" it give me a value 23 before 123. When I use the pattern "/\d+" it would give results event when the string is /23/Music/123. What I want to do is extract the only number after "/Music/" .

Upvotes: 0

Views: 3318

Answers (2)

walrii
walrii

Reputation: 3522

I think part of the problem is that you haven't defined very well (at least to us) what it is you are trying to match. I'm going to take some guesses. Perhaps one will meet your needs.

  • The number at the end of your input string. For example "/a/b/34". Use regex "\\d+$".
  • A path element that is entirely numeric. For example "/a/b/12/c" or "/a/b/34" but not "/a/b56/d". Use regex "(?:^|/)(\\d+)(?:/|$)" and get captured group [1]. You might do the same thing with lookahead and lookbehind, perhaps with "(?<=^|/)\\d+(?=/|$)".

Upvotes: 2

Zeratas
Zeratas

Reputation: 1015

If there will never be anything after the last slash could you just use a regex or string.split() to get everything after the last slash. I'd get you code but I'm on my phone now.

Upvotes: 0

Related Questions