2

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?

1
  • 2
    You should doulbe check it with a tester. Your regex will fail: regex101.com/r/tGICBc/1 Commented Mar 12, 2018 at 15:55

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

To elaborate, [.*] means "Only match one of the literal . or * characters".
".*" fails as well

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.