开发者

If-Then-Else Conditionals in Regular Expressions and using capturing group

I have some difficulties in understanding if-then-else conditionals in regular expressions.

After reading If-Then-Else Conditionals in Regular Expressions I decided to write a simple test. I use C++, Boost 1.38 Regex and MS VC 8.0.

I have written this program:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{
    std::string str_to_modify = "123";
    //std::string str_to_modify = "ttt";
    boost::regex regex_to_search ("(\\d\\d\\d)开发者_运维问答");
    std::string regex_format ("(?($1)$1|000)");

    std::string modified_str = 
         boost::regex_replace(
           str_to_modify, 
           regex_to_search, 
           regex_format, 
           boost::match_default | boost::format_all | format_no_copy );

    std::cout << modified_str << std::endl;

    return 0;

}

I expected to get "123" if str_to_modify has "123" and to get "000" if I str_to_modify has "ttt". However I get ?123123|000 in the first case and nothing in second one.

Coluld you tell me, please, what is wrong with my test?

The second example that still doesn't work :

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{
    //std::string str_to_modify = "123";
    std::string str_to_modify = "ttt";
    boost::regex regex_to_search ("(\\d\\d\\d)");
    std::string regex_format ("(?1foo:bar");

    std::string modified_str = 
        boost::regex_replace(str_to_modify, regex_to_search, regex_format, 
            boost::match_default | boost::format_all | boost::format_no_copy );

    std::cout << modified_str << std::endl;

    return 0;

}


I think the format string should be (?1$1:000) as described in the Boost.Regex docs.

Edit: I don't think regex_replace can do what you want. Why don't you try the following instead? regex_match will tell you whether the match succeeded (or you can use match[i].matched to check whether the i-th tagged sub-expression matched). You can format the match using the match.format member function.

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{
    boost::regex regex_to_search ("(\\d\\d\\d)");

    std::string str_to_modify;
    while (std::getline(std::cin, str_to_modify))
    {
        boost::smatch match;
        if (boost::regex_match(str_to_modify, match, regex_to_search))
            std::cout << match.format("foo:$1") << std::endl;
        else
            std::cout << "error" << std::endl;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜