如何获取匹配组的索引

时间:2018-05-16 14:12:04

标签: c++ regex boost

我想在输入中列出所有匹配的组。例如,我想在User-Agent HTTP标头中打印我关心的所有浏览器。一场比赛就足够了。有没有办法摆脱下面的代码中的内部for循环。我查看了boost / regex / sub_match.hpp,我没有任何想法。

#include <string> 
#include <iostream> 
#include <boost/regex.hpp> // Boost 1.59, no C++14 for me

enum BrowserType
{
    FIREFOX = 0 ,
    CHROME,
    SAFARI,
    OPERA,
    IE,
    EDGE,
    OTHER,
};

const boost::regex BROWSERS_REGEX("(Firefox)|(Chrome)|(Safari)|(Opera)|(MSIE)|(Edge)|(Trident)");

int main()
{
        // I expect two matches here CHROME and SAFARI
        std::string input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
        boost::sregex_iterator res(input.begin(), input.end(), BROWSERS_REGEX);
        boost::sregex_iterator end;
        for(; res != end; ++res)
        {
                // elude copy here ?
                boost::smatch what = *res;
                // Can I know the index of the matching group w/o 'for'?
                for (int type = 0;type < OTHER;type++) 
                {
                        int groupIndex = type+1;
                        if (what[groupIndex].matched) 
                                std::cout << (BrowserType)type << ",";
                }
                std::cout << "\n";

        }

        return 0;
}

重要更新。基于strstr()的代码是短于1K字节的字符串的最快方法

    const char *input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
    const char *browsers[OTHER+1] = {"Firefox", "Chrome", "Safari", "Opera", "MSIE", "Edge", "Trident"};
    int i = 0;
    for (const char **browser = &browsers[0];browser <= &browsers[OTHER];browser++, i++)
    {
            if (strstr(input, *browser))
            {
                    groupindex = i;
            }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用命名捕获。

我今天早些时候使用过它:While doing url encoding , The std::regex_replace doesn't work properly for character "+" . Can some body help me out?

在你的情况下,我会使用qi :: symbols:

struct browser_type_sym : boost::spirit::qi::symbols<char, BrowserType> {
    browser_type_sym() {
        this->add
            ("Firefox", FIREFOX)
            ("Chrome",  CHROME)
            ("Safari",  SAFARI)
            ("Opera",   OPERA)
            ("MSIE",    IE)
            ("Edge",    EDGE)
            ("Trident", OTHER);
    }
} static const browser_type;

您只需将其与BrowserType的任何容器一起使用:

template <typename Types>
bool extract_browser_ids(std::string const& userAgent, Types& into) {
    using boost::spirit::repository::qi::seek;
    return parse(userAgent.begin(), userAgent.end(), *seek [ browser_type ], into);
}

使用vector<BrowserType>

正如您将看到的,如果您使用vector<BrowserType,它将保留订单并重复:

<强> Live On Coliru

int main() {
    for (std::string const input : {
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94",
            "Chrome; Opera; Chrome again!"
    }) {
        std::vector<BrowserType> types;
        extract_browser_ids(input, types);
        for(auto type : types)
            std::cout << type << ",";

        std::cout << "\n";
    }
}

打印:

2,1,
1,3,1,

使用set<BrowserType>

使用set<>时,它会订购和删除重复:

<强> Live On Coliru

    std::set<BrowserType> types;

打印:

1,2,
1,3,

案例不敏感

只是为了显示小调整:

struct browser_type_sym : boost::spirit::qi::symbols<char, BrowserType> {
    browser_type_sym() {
        this->add
            ("firefox", FIREFOX)
            ("chrome",  CHROME)
            ("safari",  SAFARI)
            ("opera",   OPERA)
            ("msie",    IE)
            ("edge",    EDGE)
            ("trident", OTHER);
    }
} static const browser_type;

template <typename Types>
bool extract_browser_ids(std::string const& userAgent, Types& into) {
    using boost::spirit::repository::qi::seek;
    using boost::spirit::qi::no_case;
    return parse(userAgent.begin(), userAgent.end(), *seek [ no_case [ browser_type ] ], into);
}

现在情况并不重要: Live On Coliru

替代方案:提升Xpressive

同样,您可以使用Boost Xpressive,它稍微接近regex方法(尽管internally it still builds a trie of strings from the map)。

语义动作需要更多的手工劳动,使其也不那么通用(如果没有更改,它将无法与std::set一起使用,这与已经显示的Spirit Qi方法不同。)

然而,为了完整性:

<强> Live On Coliru

std::map<std::string, BrowserType> s_browser_type_map {
        {"Firefox", FIREFOX},
        {"Chrome",  CHROME},
        {"Safari",  SAFARI},
        {"Opera",   OPERA},
        {"MSIE",    IE},
        {"Edge",    EDGE},
        {"Trident", OTHER},
    };

#include <boost/xpressive/xpressive.hpp>
#include <boost/xpressive/regex_actions.hpp>

template <typename Types>
void extract_browser_ids(std::string const& userAgent, Types& into) {
    using namespace boost::xpressive;

    placeholder<Types> _result;
    sregex type = (a1 = s_browser_type_map) [ push_back(_result, a1) ];

    for (sregex_iterator it(userAgent.begin(), userAgent.end(), type, let(_result=into)),
            end; it != end; ++it) 
    { } // all side-effects in the semantic action
}

打印与vector<> Spirit示例相同的输出:

2,1,
1,3,1,