Не удается найти соответствие с boost xpressive динамическое регулярное выражение

Edit8: я сначала опубликовал решение для тех, кто может прийти после меня с той же проблемой.

Решение:

Назначено регулярное выражение с = вместо вызова оператора (). Работал нормально. Это было глупо.

#include <iostream>
#include <string>
#include <boost/xpressive/xpressive_dynamic.hpp>

int main()
{
    std::string str = "foobarfoo";
    boost::xpressive::sregex rex;
    std::string rstr = "foo";
    rex = boost::xpressive::sregex::compile(rstr, boost::xpressive::regex_constants::ECMAScript);
    if (boost::xpressive::regex_search(str, rex, boost::xpressive::regex_constants::match_continuous))
        std::cout << "Match found.";
    else
        std::cout << "No match found.";
    return 0;
}

Оригинальная проблема:

Я уже некоторое время борюсь с xpressive, и мне еще ничего не нужно делать. Со следующим кодом:

#include <iostream>
#include <string>
#include <boost/xpressive/xpressive_dynamic.hpp>

int main()
{
    std::string str = "foobar";
    boost::xpressive::sregex rex;
    std::string rstr = "foo";
    rex(boost::xpressive::sregex::compile(rstr));
    if (boost::xpressive::regex_match(str, rex))
        std::cout << "Match found.";
    else
        std::cout << "No match found.";
    return 0;
}

Я не нахожу того, чего ожидаю. Помощь будет принята с благодарностью.

Edit: попытался изменить строку компиляции регулярного выражения на

rex(boost::xpressive::sregex::compile(rstr, boost::xpressive::regex_constants::ECMAScript));

Еще ничего.

Edit2: компиляция с MinGW GCC 4.7

Edit3: я также попытался изменить строку, где строка регулярного выражения объявлена ​​обоим

std::string rstr = ".*";

а также

std::string rstr = "(.*)";

Еще ничего.

Edit4: я не получил следующее, но без результатов:

#include <iostream>
#include <string>
#include <boost/xpressive/xpressive_dynamic.hpp>

    int main()
    {
        std::string str = "foobarfoo";
        boost::xpressive::sregex rex;
        std::string rstr = "(foo)";
        rex(boost::xpressive::sregex::compile(rstr));//;, boost::xpressive::regex_constants::ECMAScript));
        if (boost::xpressive::regex_search(str, rex, boost::xpressive::regex_constants::match_default))
            std::cout << "Match found.";
        else
            std::cout << "No match found.";
        return 0;
    }

Edit5: я ожидаю два матча в этот момент, "Foo" в начале и в конце ул.

Edit6: попытался запустить regex_search с установленным флагом match_continuous, надеясь, что я хотя бы смог получить префикс. Нет кости. Также попытался скомпилировать с флагом ECMAScript и запустить regex_search с флагами match_default и match_continuous.

Edit7: я знаю, что strstr() будет работать здесь. Это потому, что это простой пример. Повышение обязательно в реальном приложении.

2 ответа

Решение
#include <iostream>
#include <string>
#include <boost/xpressive/xpressive_dynamic.hpp>

int main()
{
    std::string str = "foobar";
    std::string rstr = "foo";
    boost::xpressive::sregex rex = boost::xpressive::sregex::compile(rstr);
    if (boost::xpressive::regex_search(str, rex))
        std::cout << "Match found." << std::endl;
    else
        std::cout << "No match found." << std::endl;
}

Печать "Match found." для меня. Если вы хотите найти все совпадения...

#include <iostream>
#include <string>
#include <boost/xpressive/xpressive_dynamic.hpp>

int main()
{
    std::string str = "foobarfoo";
    std::string rstr = "foo";
    boost::xpressive::sregex rex = boost::xpressive::sregex::compile(rstr);
    boost::xpressive::sregex_iterator it(str.begin(), str.end(), rex), end;

    for (; it != end; ++it )
        std::cout << "Match found at offset "
                  << ((*it)[0].first - str.begin())
                  << std::endl;
}

Для меня это печатает:

Совпадение найдено по смещению 0
Совпадение найдено по смещению 6

Пытаться regex_search вместо regex_match?

Повышение документов для regex_match государство:

Обратите внимание, что результат имеет значение true, только если выражение соответствует всей входной последовательности. Если вы хотите найти выражение где-то в последовательности, используйте regex_search, Если вы хотите сопоставить префикс строки символов, используйте regex_search с флагом match_continuous задавать.

http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/ref/regex_match.html

Другие вопросы по тегам