Regular Expression Boost Library Regex_Search Match Error

when i use boost::regex_search function to do something like this

std::string sTest = "18";
std::string sRegex = "^([\\u4E00-\\u9FA5]+)(\\d+)(#?)$";
std::string::const_iterator iterStart = sTest.begin();
std::string::const_iterator iterEnd = sTest.end();
boost::match_results<std::string::const_iterator> RegexResults;

while (boost::regex_search(iterStart, iterEnd, RegexResults, boost::regex(sRegex)))
{
    int a = 1;
    break; 
}

however value 'stest' is matched,but when i use std::regex_search it's ok.

1

1 Answer

Assuming the question is serious:

the regex matches

  1. ^ (start of input)

  2. What looks like you intended as one or more of the "CJK Unified Ideographs" block (though only from the 1.0.1 Unicode standard).

    However, this is not what is parsed. (Instead, indeed it parses as regular hex escapes which does match 1).

    The docs tell me that you might have wanted \x{dddd} but that requires Unicode support.

    Digging in more docs tell me that

    There are two ways to use Boost.Regex with Unicode strings:

    Rely on wchar_t

    (lists a bunch of limitations and conditions)

    Use a Unicode Aware Regular Expression Type.

    May I suggest the latter

  3. one or more numerical digits (according to the locale's character classicification)

  4. (#?) might have been intended as a comment ((?#)) but as spelled optionally matches a single # character

  5. followed by $ (end of input)

That's not in your input, so it shouldn't match.

Off Topic?

Besides, since this is a fully anchored pattern (^$) it would only make sense with regex_match, not regex_search.

The while loop is a weird idea, because the input never changes, so neither will the search result. If there's a match, the loop always breaks. Your while amounts to a more confusing if statement.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.