如何让正则表达式匹配句子中间?

How to have regex to match middle of sentence?

本文关键字:句子 中间 正则表达式      更新时间:2023-10-16

我试图让正则表达式匹配字符串上的某些内容,然后捕获字符串的其余部分。根据 https://regex101.com/下面的正则表达式应该可以工作,但事实并非如此。似乎 c++ 正则表达式只会从字符串的开头匹配。如何让它从字符串的中间开始?我知道我可以.*?/word(.*)但我宁愿不这样做,因为正则表达式是用户输入......

std::string uri("a/word/");
std::smatch match;
std::regex rgx(R"(/word(.*))");
if (std::regex_match(uri, match, rgx)) {
std::cout << match[0] << ' ' << match[1];
}

regex_match应该匹配整个输入序列,而不是其中的一部分。对于后者,您需要regex_search.

使用它,您的示例打印/word/ /.

现场演示