Reputation: 11
I need to validate input, only 2 or 3 digits should be allowed.
I am not sure why boost::regex_match is returning true for 4 digits scenario ?
boost::smatch base_match;
boost::regex base_regex("[0-9]{2,3}");
std::string same_digits("1234"));
if (boost::regex_match(same_digits, base_match, base_regex))
{
std::cout << " It is True!"<< std::endl;
}
How to write boost regex to get result like ^[0-9]{2,3}$
Upvotes: 1
Views: 332
Reputation: 393114
I'm also not sure. This is what I see:
#include <boost/regex.hpp>
#include <iostream>
#include <iomanip>
int main() {
boost::smatch m;
boost::regex r("[0-9]{2,3}");
for (std::string const input :
{"", "1", "12", "123", "1234", "12345"}) //
{
std::cout << std::quoted(input) << " -> " << std::boolalpha
<< regex_match(input, m, r)
<< std::endl;
}
}
Prints
"" -> false
"1" -> false
"12" -> true
"123" -> true
"1234" -> false
"12345" -> false
Note that this is different from regex_search
. You need the ^$
anchors there: Compare http://coliru.stacked-crooked.com/a/a89fe8931d04ad99 to http://coliru.stacked-crooked.com/a/a430319477fa3b52
Upvotes: 1