std::string to std::regex

std::string to std::regex

本文关键字:std regex string to      更新时间:2023-10-16

我正在尝试将字符串转换为正则表达式,字符串如下所示:

std::string term = "apples oranges";

我希望regexterm的,所有空格都替换为任何字符和任何长度的字符,我认为这可能会起作用:

boost::replace_all(term , " " , "[.*]");
std::regex rgx(s_term);

因此,在std::regex_search term查看时会返回 true:

std::string term = "apples pears oranges";

但它没有成功,你如何正确地做到这一点?

你可以

basic_regex做所有事情,不需要boost

#include <iostream>
#include <string>
#include <regex>
int main()
{
    std::string search_term = "apples oranges";
    search_term = std::regex_replace(search_term, std::regex("\s+"), ".*");
    std::string term = "apples pears oranges";
    std::smatch matches;
    if (std::regex_search(term, matches, std::regex(search_term)))
        std::cout << "Match: " << matches[0] << std::endl;
    else
        std::cout << "No match!" << std::endl;
    return 0;
}

https://ideone.com/gyzfCj

这将在发现第一次出现apples<something>oranges时返回。如果需要匹配整个字符串,请使用 std::regex_match

您应该使用没有[]boost::replace_all(term , " " , ".*");.*只是意味着任何字符,以及任意数量的字符。