Reputation: 41
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.
Upvotes: 2
Views: 1920
Reputation: 70732
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';
}
Upvotes: 4
Reputation: 41838
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
Upvotes: 0
Reputation: 137330
std::regex_match
reports an exact match, i.e., the entire input string must match the regex.
To match subsequences, use std::regex_search
.
Upvotes: 4