Reputation: 339
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?
Upvotes: 2
Views: 3339
Reputation: 6240
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;
}
This will return when 1st occurrence of apples<something>oranges
found. If you need match the whole string, use std::regex_match
Upvotes: 4
Reputation: 7220
You should use boost::replace_all(term , " " , ".*");
that is without the []
. The .*
simply means any character, and any number of them.
Upvotes: 2