Home > Mobile >  How to use string variable multiple times to make regex expression
How to use string variable multiple times to make regex expression

Time:12-23

Just wanting to use a string variable multiple times in the construction of my regex variable. I want to match on a word whether it is the word itself or the same word with a number appended at the end of it (up to two digits) For example, suppose I have this:

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";
}

CodePudding user response:

You need to concatenate your str1 variable with string literals that represent the remaining pieces of the regex expression, eg:

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

Alternatively, you can avoid the duplication of str1 using C 20's std::format() (or equivalent), for instance:

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

However, that being said, since you are really just looking for a single word with an optional number following it, you can simplify the regex expression to this instead:

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