In article <73b61208-0920-43d3-b9e2-a901dc7d8b55
@m73g2000hsh.go oglegroups.com> ,
na************@ googlemail.com says...
[ ... ]
Sorry for not being clear, i just wanted a simple pattern matcher not
using regular expressions, i think this is too much
The match pattern can contain the wildcard characters "*" and "?",
where "*" matches zero or more consecutive occurrences of any
character and "?" matches a single occurrence of any character
The std::string does not have such a match function which returns a
bool
I tend to agree -- given that the matching itself only takes up
something like 4 lines of code, it's probably easier to do the match
than convert to an RE, and then use an RE engine to do the job.
#include <string>
#include <functional>
class patmat : public std::unary_func tion<char const *, bool{
std::string pat;
bool match(char const *pat, char const *str) const {
switch (*pat) {
case '\0': return *str=='\0';
case '*':
return match(pat+1, str) || *str && match(pat, str+1);
case '?': return *str && match(pat+1, str+1);
default: return *pat==*str && match(pat+1, str+1);
}
}
public:
patmat(std::str ing pattern) : pat(pattern) {}
bool operator()(std: :string const &str) const {
return(match(pa t.c_str(), str.c_str()));
}
};
#ifdef TEST
#include <iostream>
#include <vector>
#include <algorithm>
void test(char const * const *strings, size_t num, std::string pat) {
std::cout << "\nTesting against " << pat << "\n";
std::remove_cop y_if(strings, strings+num,
std::ostream_it erator<std::str ing>(std::cout, "\n"),
std::not1(patma t(pat)));
}
int main() {
char *test_strings[] = {
"longstring ",
"a really, really long string, compared to the others",
"string",
"spring",
"a string"
};
std::cout<< "Test strings:\n";
std::copy(test_ strings, test_strings+4,
std::ostream_it erator<std::str ing>(std::cout, "\n"));
test(test_strin gs, 5, "a*");
test(test_strin gs, 5, "*g");
test(test_strin gs, 5, "*s?r*g");
test(test_strin gs, 5, "*st*g");
return 0;
}
#endif
--
Later,
Jerry.
The universe is a figment of its own imagination.