简体   繁体   中英

std::string to std::regex

I'm trying to convert a string to a regex, string looks like so:

std::string term = "apples oranges";

and I wanted the regex to be term with all spaces replaced by any character and any length of characters and I thought that this might work:

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

so in std::regex_search term would return true when looking at:

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

but its not working out, how do you do this properly?

You could do everything with basic_regex , no need for 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

This will return when 1st occurrence of apples<something>oranges found. If you need match the whole string, use std::regex_match

You should use boost::replace_all(term , " " , ".*"); that is without the [] . The .* simply means any character, and any number of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM