2

I've tried to implement a simple string-test method using c++ std::regex, in MS VC++ 2012.

const std::string str = "1.0.0.0029.443";

if ( std::regex_match( str, std::regex( "\\.0\\d+" ) ) )
    std::cout << "matched." << std::endl;

I guessed that the code would match ".0029" part of the given str. However, it doesn't match at all. I tried it on http://regex101.com/ and it worked.

3 Answers 3

4

Use std::regex_search instead to return your submatch.

const std::string str = "1.0.0.0029.443";

std::regex rgx("(\\.0[0-9]+)");
std::smatch match;

if (std::regex_search(str.begin(), str.end(), match, rgx)) {
    std::cout << match[1] << '\n';
}
Sign up to request clarification or add additional context in comments.

Comments

4

std::regex_match reports an exact match, i.e., the entire input string must match the regex.

To match subsequences, use std::regex_search.

Comments

0

To ensure your regex matches the full string and nothing else, you need something like this:

^(?:\d+\.)*\d+$

This translates into

if ( std::regex_match( str, std::regex( "^(?:\\d+\\.)*\\d+$" ) ) )
    std::cout << "matched." << std::endl;

The beginning and end of anchors ^ and $ are required, otherwise you might match a string in the middle of BANANA_0.1.12AND_APPLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.