我试图将字符串转换为正则表达式,字符串如下所示:
std::string term = "apples oranges";
我希望regex
是term
,用任何字符和任意长度的字符替换所有空格,我认为这可能会奏效:
boost::replace_all(term , " " , "[.*]");
std::regex rgx(s_term);
因此,在std::regex_search
中,term
在查看以下内容时将返回true:
std::string term = "apples pears oranges";
但这不管用,你怎么才能做好呢?
发布于 2018-03-12 16:50:58
你可以用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;
}
这将在第一次发现apples<something>oranges
时返回。如果需要匹配整个字符串,请使用std::regex_match
发布于 2018-03-12 15:55:03
您应该使用没有boost::replace_all(term , " " , ".*");
的[]
。.*
只是指任何字符,以及任意数量的字符。
https://stackoverflow.com/questions/49239384
复制相似问题