如何多次使用字符串变量来生成正则表达式



只是想在构造正则表达式变量时多次使用字符串变量。我想匹配一个单词,无论它是单词本身还是在其末尾附加数字的相同单词(最多两个数字)。例如,假设我有这样的内容:

string str1 = "MyWord";    //I want this to pass
string str2 = "MyWord2";   //I want this to pass
string str3 = "MyWor";     //I want this to fail
//This works, but I don't want to use a string literal, I want to use str1
const regex re("MyWord|MyWord\d{1,2}");
//I need the variable to be used multiple times in the regex
const regex re(str1 | str1\d{1,2}) 

if (regex_match (str2, re )){
cout << "We have a match";
}

您需要将您的str1变量与表示regex表达式其余部分的字符串字面值连接起来,例如:

const regex re(str1 + "|" + str1 + "\d{1,2}");

或者,您可以使用c++ 20的std::format()(或同等的)来避免str1的重复,例如:

const regex re(format("{0}|{0}\d{{1,2}}", str1));

然而,话虽如此,由于您实际上只是在查找后跟可选数字的单个单词,因此您可以将正则表达式简化为:

const regex re(str1 + "\d{0,2}");

最新更新