Hi people,
I'm trying to match strings from a pattern containing wildcards.
Basically I need to be able to go through a stack of strings, and see which of them matches my pattern.
Fx My*.txt will match only one of these.
MyFile.txt
MyFile.php
I'm aiming to end up with a function like this, which returns all matching strings.
std::vector<std::string> matchStrings(const std::string& pattern, const std::vector<std::string>& stringsToMatch);
I've been thinking a lot about this, and wrote many different codes to do this, but I cannot think of a way that works in all scenarios. I'd also like it to be efficient.
If anyone can point out a free-to-use code available, which does this, please point me there :) This is not some school homework that I must achieve myself. I already did google without luck.
Otherwise, please post your ideas or experiences on this subject.
My current attempt is posted below, although it doesn't get far. I stopped, as I realised it wouldn't work in some scenarios, where the non-wildcard parts of the pattern occurs multiple times.
#include <iostream>
#include <string>
#include <vector>
typedef std::string String;
typedef std::vector<String> Stringvector;
int main(int argc, char** argv)
{
Stringvector strings;
strings.push_back("MyNotes.txt");
strings.push_back("Groceries.txt");
strings.push_back("MyCarPlates.txt");
Stringvector matches;
String pattern = "My*.txt";
Stringvector texts;
{ // split the pattern into separate strings, separated by wildcards
String::size_type pos = pattern.find("*");
while(pos != String::npos)
{
texts.push_back(pattern.substr(0, pos));
pattern.replace(0, pos+1, "");
pos = pattern.find("*");
}
texts.push_back(pattern);
pattern = "";
}
for(Stringvector::const_iterator it = strings.begin(); it != strings.end(); ++it)
{
String str = *it; // temporary string
for(Stringvector::const_iterator it = texts.begin(); it != texts.end(); ++it)
{
String::size_type pos = str.find(*it);
while(pos != String::npos)
{
str.replace(pos, (*it).length(), "#"); // let's temporarily pinpoint non-wildcard pattern matches
pos = str.find(*it);
}
}
}
return 0;
}
I appreciate your assistance ;)