The regular expression matches one of two file name patterns.
I am trying to match filenames using boost::regex
and I have two types of patterns:
-
XYZsomestring
-
XYsomestringENDING
The string somestring
can be anything (> 0 characters). The beginning of the file name is XYZ
or XY
. If it is XY
, there must be a line ENDING
that ends the entire sequence. I tried to combine two regex with |
but it doesn't work. This matches filenames with the first pattern:
(XYZ)(.*)
and this matches the filenames with the second pattern:
(XY)(.*)(ENDING)
But when I combine them, only the first pattern matches:
((XYZ)(.*))|((XY)(.*)(ENDING))
This is all assumed to be case insensitive, so I use it boost::regex::icase
in the constructor. I tried this without it icase
, doesn't work either).
Any suggestions?
source to share
There could be simpler expressions, but I think the regex ^xy(?(?!z).*ending$|.*$)
should do this:
#include <iostream>
#include <string>
#include <boost/regex.hpp>
bool bmatch(const std::string& x, const std::string& re_) {
const boost::regex re(re_, boost::regex::icase);
boost::smatch what;
return boost::regex_match(x, what, re);
}
int main()
{
std::string re = "^xy(?(?!z).*ending$|.*$)";
std::vector<std::string> vx = { "XYZ124f5sf", "xyz12345",
"XY38fsj dfENDING", "xy4 dfhd ending",
"XYZ", "XY345kENDI", "xy56NDING" };
for (auto i : vx) {
std::cout << "\nString '" << i;
if (bmatch(i, re)) {
std::cout <<
"' was matched." << std::endl;
} else {
std::cout <<
"' was not matched." << std::endl;
}
}
return 0;
}
Here's a live demo .
Edit:
Also, I think regex ^xy(z.*|.*ending)$
should work as well.
source to share